Shad Shad - 5 months ago 27
Java Question

Confusion Regarding Constructor Chaining in Java

From what I understand about Constructor Chaining is that

Whenever we create an object of child class (or call child class constructor) a
call to default constructor of parent class is automatically made first ONLY IF

our child constructor does not happen to call another constructor either using this (for same class) or super keyword. source:

So if my understanding is correct

Then for the following code:-

Class First{

Class Second extends First{

Second(int i)
this(2); //default constructor is calling another constructor using this keyword

public static void main(String[] args)
Second ob = new Second();

Output should be

But the output is

So it seems the default constructor of parent class is still being called indeed.
But quoting from that source:-

2) If you do not call another constructor either from parent class or same class than Java calls default or no argument constructor of super class.

Read more:

So please help out!

Answer Source

The basic rule is that one way or another a superclass constructor is always called. There is no trick out of this rule* and for good reason: the subclass relies on the state of the superclass, so if the superclass is not initialised, the subclass behaviour is incorrect. (Think of inherited protected fields for example.)

If you add an explicit call to super(...) (you can choose which super constructor to call here), then that will be called, otherwise super() (with no arguments) will be called implicitly from any constructor that doesn't call another using this(...).

In your case the chain is as follows: Second() -> Second(int) -> First(). The first call is explicit (this(2)), the second is implicit.

*For nitpickers, this statement is obviously not true if you use deserialisation or Unsafe. :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download