Constructor Chaining in Java

Hopefully you have gone through Java Constructors before coming here.

As shared in Java Constructors, Java compiler adds super() implicitly as the first line of the constructor, in case it is not there in the constructor.

 

Let’s use the below hierarchy for our example. Here C extends B. B in turn extends A.

Once when you create an instance of C. The constructor of C will invoke internally constructor of B , which will in turn invoke the constructor of A.

Screen Shot 2020-05-17 at 6.26.38 PM
package com.java.core;

class A {

    public A() {
        System.out.println("Invoking Constructor of A");
    }

}

class B extends A {

    public B() {
        System.out.println("Invoking Constructor of B");
    }

}

class C extends B {

    public C() {
        System.out.println("Invoking Constructor of C");
    }

}

public class ConstructorChaining {

    public static void main(String[] args) {
        C c = new C();
    }

}
Invoking Constructor of A
Invoking Constructor of B
Invoking Constructor of C

Points to Note

Java Compiler only adds no args constructor of Super Class. If you want to invoke a parameterized constructor of Super Class, then you have to explicitly add that as the first line of the constructor.

package com.java.core;

public class Example extends SuperClass {

    public Example() {
        super(10); // Invoking parameterized super class constructor implicitly 
        System.out.println("Invoking No args Constructor");
    }

    public static void main(String[] args) {
        Example example = new Example();
    }

}

class SuperClass {

    int id;

    SuperClass(int id) {
        System.out.println("Invoking Parameterized SuperClass Constructor");
        this.id = id;
    }
}
Invoking Parameterized SuperClass Constructor
Invoking No args Constructor

Leave a Reply

Your email address will not be published. Required fields are marked *