• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Default constructor

 
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
source : Enthuware

Which of the following constructors MUST exist in SuperClass for SubClass to compile correctly?


given answers:
public SuperClass(int a);
public SuperClass();


Why do we need the default constructor in this case? The only constructor that the subclass uses of superclass is the one that takes an int. Not sure why we need the no-arg constructor for the subclass point of view.
 
Meena R. Krishnan
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Got it!
The subclass constructor SubClass(int, int), since it is not explicitly calling the super class constructor, a default no-arg constructor of the superClass will be inserted in order for it to get constructed and that's why the need for the no-arg constructor.
 
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thats great man!!!
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by M Krishnan:
... The subclass constructor SubClass(int, int), since it is not explicitly calling the super class constructor, a default no-arg constructor of the superClass will be inserted in order for it to get constructed and that's why the need for the no-arg constructor.


Just to be clear: Without an explicit call to super (or this), an implicit call to the superClass no-args constructor will be inserted in the subclass constructor.

The compiler will add a default no-args constructor to the superClass only if no other constructors are defined. Otherwise, it is left to the programmer to write the no-args constructor.
 
reply
    Bookmark Topic Watch Topic
  • New Topic