Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Default constructor

 
Meena R. Krishnan
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • 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
  • 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.
 
krishna bulusu
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thats great man!!!
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic