Tuesday, 21 April 2015

Constructor Chaining in Java

What is Constructor Chaining

In case when we have a hierarchy of classes (in case of inheritance) it is important to know the order in which constructors for the classes are executed. That order is known as constructor chaining.
There is also concept of constructor overloading where, with in the same class there are multiple constructor with different signatures.

How does Constructor Chaining work

If class A is superclass and there is Class B which is subclass of A. In that case if a new instance of class B is created what is the order in which constructors of Class A and Class B are executed?
Answer is; the order followed is from superclass to subclass. Subclass can call a constructor in the superclass inside one of the subclass constructors explicitly using super(). In that case super() must be the first statement in a subclass constructor. If super() is not used then the default no-arg constructor of each superclass will be executed implicitly. Note that the order remains same (from superclass to subclass ) whether or not super() is used.

Let's see it with an example -

class A{
  System.out.println("In class A's constructor");

class B extends A{
  System.out.println("In class B's constructor");
class C extends B{
  System.out.println("In class C's constructor");
public class ConstrChaining {

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



It can be noticed here that we have a multilevel inheritance where super class is A which is extended by B and B is extended by C. When the instance of C is created it will trigger the chain of constructor invocations starting from the constructor of class A, then class B and at the last constructor of class C.
It can be seen from the output of the program

In class A's constructor
In class B's constructor
In class C's constructor

It can be seen from the program that I have explicitly called the constructor of B from the constructor of class C using super() where as in the constructor of class B there is no super still the constructor of class A is called because default no-arg constructor of super class will be executed implicitly in that case.

That's all for this topic Constructor chaining in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Related topics

  1. Constructor in Java
  2. Constructor overloading in Java
  3. Inheritance in Java
  4. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

No comments:

Post a Comment