Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance Question

 
Swati Singhal
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am a lil confused with this question. Appreciate if somebody could clarify.
Which of the following constructors must exist in Parent class?

I thought the answer would be c, but it is both a & c.
 
Gian Franco
blacksmith
Ranch Hand
Posts: 979
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Swati,

Given the two constructor in the Child class both
a and c must be added, because for the latter an
explicit call is done with super(i,j). The former
is called by the default no-argument constructor
that JVM inserts in the Child(int i) constructor
as the first line of code.
You have to add the no-argument constructor
actually because you just had to add
public Parent(int i, int j). Normally the JVM
creates a default no-argument constructor
for you, but with one condition: there must NOT
be any other constructor.
HTH,
Gian Franco
 
Richard Quist
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Swati Singhal:
Hi,
I am a lil confused with this question. Appreciate if somebody could clarify.
Which of the following constructors must exist in Parent class?

I thought the answer would be c, but it is both a & c.

You need both because the Child constructor public Child(int i){ } has an implicit call to the compiler-provided, default, no-arg constructor of the parent (answer A).
Answer C is needed because of the explicit call to super(i,j); in the Child constructor public Child(int i, int j)
Also note that the method public void Child(int i, int j, int k) is NOT a constructor - since constructors don't have return types (and this method is declared to return void)
Hope this helps
 
Vicken Karaoghlanian
Ranch Hand
Posts: 522
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler will do an implicit call to the no-args constructor in the super class parent.


That is why this code doesn't compile, to allow the compilation, you must provide a no argument constructor in the super class, see code:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic