Confusion Regarding Constructor Chaining in Java

849 views Asked by At

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: http://www.java67.com/2012/12/how-constructor-chaining-works-in-java.html

So if my understanding is correct

Then for the following code:-

Class First{
    First(){
    System.out.print("Hello");
    }

Class Second extends First{

    Second(int i)
    {
    System.out.println("Blogger");
    }
    Second(){
    this(2);    //default constructor is calling another constructor using this keyword
    }


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

Output should be Blogger only.

But the output is HelloBlogger

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: http://www.java67.com/2012/12/how-constructor-chaining-works-in-java.html#ixzz4qztuMrKW

So please help out!

2

There are 2 answers

1
biziclop On BEST ANSWER

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. :)

2
shmosel On

Yes, the default constructor only calls this(int), but this(int) implicitly calls super(). It's impossible to make a constructor that doesn't eventually call some form of super().