Constructor Chaining in Java (with Example)

Constructor chaining in Java is a technique of calling one constructor from within another within the same class or between a parent and child class. This technique helps reuse code and reduce redundancy when initializing objects in different ways.

Java provides two keywords for constructor chaining: this and super.

  • The keyword “this” is used to call one constructor from another within the same class.
  • The keyword “super” is used to call the parent class (superclass) constructor from within child class (subclass) constructor. This occurs through inheritance.

We cannot call the constructor directly by name because it is illegal in Java. Instead, you must use this() or super(). When you will implement constructor chaining technique in Java, it is important to understand the order in which constructors will execute, especially in the context of inheritance.

Order of Execution of Constructor in Inheritance Relationship


When you create a subclass object, the subclass constructor first calls its superclass constructor before executing its own statements. If the superclass is derived from another class, it will call its own superclass constructor before executing its own statements.

This process continues until it reaches the last chained constructor and the end of the chain will always be the constructor of the Object class. This is because every class is inherited from the Object class by default. In other words, Object class is the root class of all Java classes. This entire process is known as constructor chaining in Java. That means if you create an object of subclass, all its superclasses are also instantiated in a top-down order.

Example of Constructor Chaining (Using this and super)

To understand the constructor chaining process, look at the below figure. In this figure, a class named “College” contains three constructors:

  • Default constructor
  • One parameter constructor
  • Two parameters constructor

When you create an object of College by passing two arguments to its constructor, the following things occur:

  • The new keyword will immediately trigger two parameters constructor call.
  • Inside two-parametrized constructor, the statement this(name); calls one parameter constructor.
  • The statement this(); inside the one-parameter constructor calls the default constructor.
  • At last, inside the default constructor, the compiler implicitly places a call to super() to invoke the constructor of the Object class.

Since all classes in Java inherit from java.lang.Object by default, the final constructor in the chain is always the constructor of the Object class. That’s the order of execution.

An example of constructor chaining in Java using this keyword in the same class.

You cannot change the execution order of constructors arbitrarily. Constructor chaining always follows a strict top-down order. However, you can control the flow within a class using this() and across classes using super(), but you must follow the rules.

Rules for Using this and super in Constructor Chaining in Java


When you are performing constructor chaining in Java, you must following these rules:

  • The call to this() or super() must be the first statement in a constructor.
  • You cannot use both this() and super() in the same constructor. If you try to do so, a compile-time error will occur because only one constructor call is allowed as the first statement.
  • If there is no explicit call to super(), the Java compiler will automatically insert a call to the default constructor of the superclass. This happens only if the superclass has a no-argument constructor.
  • Only one constructor can call (this() or super()) is allowed in a constructor. You must choose either this() or super(). Calling both is not permitted.
  • There must be at least one constructor without this keyword.

Why do We Use Constructor Chaining in Java?


In Java programming, constructor chaining is used where you want to perform multiple initialization tasks in separate constructors for each task and control the order of execution by chaining them together.

This technique improves code readability and maintainability by avoiding code duplication. You can make the program more readable and easy to understand for everyone. You can define as many constructors as needed within a class, and use constructor chaining to connect them in a logical sequence.

Example of Constructor Chaining using this Keyword


If we need to call the same or current class constructor within the same class, you use this Keyword. The syntax to call the same class constructor using this keyword is as follows:

this();
Or,
this(argument);

The statement this(argument) invokes the same class constructor with types of parameters that must match. For example:

  • this();  ➨ To call default current class constructor.
  • this(“name”);  ➨ To call one parameter current class constructor with passing string argument.
  • this(“shubh”, 24)  ➨ To call two parameters current class constructor with passing string and int argument.


You must use this keyword to call the current class constructor because the Java compiler does not automatically insert a call to this() like it does with super().

Use of this keyword to call the current class constructor.

Example 1:

Let’s write a Java program where we will perform constructor chaining using this keyword. We will call the current class constructor from another. Look at the example code and follows all steps explained in the program.

package constructorProgram; 
public class Developed 
{ 
// Create a default (no-argument) constructor.
   Developed() 
   { 
     System.out.println("Java was developed by James Gosling"); 
   }
// Create one parameter constructor. 
   Developed(int year) 
   { 
  // Declaration of this keyword with two parameters. It must be the first line. 
     this("Java" , 1995); // It will call two parameters constructor within the same class. 
     System.out.println("James Gosling is known as Father of Java programming language."); 
   } 
// Create two parameters constructor.
   Developed(String name, int year) 
   { 
  // Declaration of this keyword without the parameter. 
     this(); // It will call default constructor due to no parameter in this keyword. 
     System.out.println("at Sun Microsystem and released in 1995"); 
   } 
// Define an instance method. 
   void display() 
   { 
     System.out.println("The Java compiler is written in Java but Java runtime in ANSI C."); 
   } 
// Create a main method. 
   public static void main(String[] args) 
   { 
  // Create an object of class Developed using the new keyword.
  // And passes the integer argument to its one parameter constructor. 
     Developed obj = new Developed(1995); // It will call one parameter constructor. 

  // Call display method using object reference variable obj. 
     obj.display(); 
  } 
}
Output: 
       Java was developed by James Gosling 
       at Sun Microsystem and released in 1995 
       James Gosling is known as Father of Java programming language. 
       The Java compiler is written in Java but Java runtime in ANSI C.

Explanation:

1. When the statement Developed obj = new Developed(1995); will be executed by JVM, it will immediately call one parameter constructor. As a result, the control of execution will be transferred to that constructor.

2. From inside one parameter constructor, the statement this(“Java”, 1995); will call two parameters constructor. Now, the control of execution is transferred to two parameters constructor.

3. From inside two parameters constructor, the statement this() will call non-parameterized constructor. Now the Java compiler changed non-parameterized constructor like this:

Developed() {
  super();
  System.out.println("Java was developed by James Gosling");
}

Inside the non-parameterized constructor, the keyword super() immediately calls its superclass class constructor (i.e. Object class constructor). After the complete execution of non-parameterized constructor, the control of execution is again transferred to two parameters constructor.

4. After the complete execution of two parameters constructor, the control of execution is again transferred to one parameter constructor.

In this way, the order of calling one constructor from another constructor is processed in the constructor chaining mechanism. At last, obj.display(); will call method to print message on the console.

Example 2:

Let’s write a Java program based on constructor chaining in which we will define default constructor and two parameterized constructors. We will call constructors using this keyword from within another class. Look at the below example code.

package constructorProgram; 
public class Protein 
{ 
// Declaration of encapsulated instance variable. 
   private String gender; 
   private int need; 
   private String source; 

   Protein() 
   { 
      this("female", 46); 
      System.out.println("Protein requirement for children above 9 years old: 36 gm/day"); 
   } 
   Protein(String s, int need) 
   { 
      this("male" , 56 , "milk"); 
      System.out.println("Protein requirement for women: 46 gm/day"); 
   } 
   Protein(String gender, int need, String source) 
   { 
      this.gender = gender; 
      this.need = need; 
      this.source = source; 
      System.out.println("Protein requirement for men: 56 gm/day"); 
   } 
}
public class ProteinTest { 
public static void main(String[] args) 
{ 
   Protein p1 = new Protein(); 
   Protein p2 = new Protein("female",46); 
   Protein p3 = new Protein("male", 56, "milk"); 
  } 
}
Output: 
       Protein requirement for men: 56 gm/day 
       Protein requirement for women: 46 gm/day 
       Protein requirement for children above 9 years old: 36 gm/day 
       Protein requirement for men: 56 gm/day 
       Protein requirement for women: 46 gm/day 
       Protein requirement for men: 56 gm/day

Explanation:

When JVM executes the statement Protein p1 = new Protein();, it will immediately call non-parameterized constructor. Inside the non-parameterized constructor, the statement this(“female”, 46); calls two parameterized constructor.

Inside it, the statement this(“male” , 56 , “milk”); calls three parameters constructor. After the complete execution of three parameters constructor, the program control again goes back to two parameters constructor and executes statements inside it. Then, the program control again goes back to non-parameterized constructor and executes the statement inside it.

 Example of Constructor Chaining using super Keyword


If we need to call the superclass constructor from the subclass constructor, you use super keyword in the subclass constructor. The syntax to call a superclass constructor using super keyword is as follows:

super();
Or,
super(argument);

The statement super() calls the no-argument constructor of its superclass and the super(argument) invokes the superclass constructor where the argument must match. For example:

  • super(); ➨ To call the default superclass constructor.
  • super(24); ➨ To call the superclass constructor with one int parameter.

You should use the super keyword to call the superclass constructor but if you do not put a super keyword, Java compiler will put automatically the super() keyword. The super keyword must be in the first line of the constructor. Calling a superclass constructor’s name in a subclass causes a syntax error.

A constructor is used to create an object of a class. Unlike properties and methods, the constructor of superclass cannot be inherited in the subclass. However, it can be called from the subclass constructor by using super keyword.

Example 4:

Let’s write a Java program in which we will perform constructor chaining using super keyword between parent class constructor and child class constructor.

package constructorProgram;
public class Parent {
 Parent() 
 {
  // super(); // This statement calls Object class constructor.
     System.out.println("I am parent constructor"); 
 }
}
// Here, extends is used for developing inheritance between two classes.
public class Child extends Parent {
  Child() {
  // super(); // This statement calls parent class constructor.
     System.out.println("I am child constructor");
  }
public static void main(String[] args) {
// Create an object of class.
   Child c = new Child();
  }
}
Output:
      I am parent constructor
      I am child constructor

In this example, constructor of child class calls parent class no-argument constructor. Java compiler changed parent class and child class constructors like this:

Parent() {
  super();
  System.out.println("I am parent constructor");
}
Child() {
  super();
  System.out.println("I am child constructor");
}

Here, the super keyword refers to the direct parent class of current object. Since super is invoked from a child class, it represents a reference to the parent class.

Example 4:

Let’s create a Java program based on constructor chaining where we will use both this and super keywords to call current class and superclass constructors.

package constructorProgram; 
public class School 
{ 
 // Declare instance variables. 
    String stName; 
    int stRoll; 
    int stId; 
    School(String schoolName) 
    { 
   // This statement calls one parameter current class constructor by passing integer value within the same class. 
       this(2); 
       System.out.println("Student's Detail: "); 
    } 
    School(int s) 
    { 
       System.out.println("Delhi Public School"); 
    } 
    School(String stName, int stRoll, int stId) 
    { 
    // This statement calls one parameter current class constructor by passing string argument within same class.
       this("DPS"); . 
       this.stName = stName; 
       this.stRoll = stRoll; 
       this.stId = stId; 
    } 
    void display() 
    { 
       System.out.println("Name: " +stName); 
       System.out.println("Roll no. : " +stRoll); 
       System.out.println("Id: " +stId); 
    } 
}
public class Student extends School // extends is used for developing inheritance between two classes. 
{ 
  Student() 
  { 
     super("Shubh" , 2 , 2345); // It will call super class constructor with passing three argument values. 
  } 
  Student(String schoolName) 
  { 
     this(); 
  } 
public static void main(String[] args) { 
// Create an object of the class School and pass string to its constructor. 
   Student st = new Student("DPS"); // Calling one parameter const. of same class. 
   st.display(); 
  } 
}
Output: 
       Delhi Public School 
       Student's Detail: 
       Name: Shubh 
       Roll no. : 2 
       Id: 2345

Example 5:

package constructorProgram; 
public class Proteins { 
  Proteins() 
  { 
    System.out.println("Protein is one of the basic building blocks of the Human body. "); 
    System.out.println("Hair, Skin, Eyes, Muscles, and organs are all made up of Protein"); 
  } 
}
public class Source extends Proteins { 
  Source() 
  { 
    this(1); 
    System.out.println("Source of Proteins are milk, eggs, meat, pulses, soybeans"); 
  } 
  Source(int s) 
  { 
 // Here, we have not placed super() keyword. 
 // Compiler will automatically put the super() keyword.
 // JVM calls superclass constructor. 
    System.out.println("Proteins are made up of amino acids"); 
  }
}
public class MyProtein { 
public static void main(String[] args) 
{ 
   Source sc = new Source(); 
 } 
}
Output: 
       Protein is one of the basic building blocks of the Human body. 
       Hair, Skin, Eyes, Muscles, and organs are all made up of Protein 
       Proteins are made up of amino acids 
       Source of Proteins are milk, eggs, meat, pulses, soybeans

Object Class: Superclass of All Classes


Java language contains a class named Object from which all classes are derived. Object class does not have any superclass. Thus, Object class is the parent of all classes in Java.

Any number of intermediate classes can be between Object and another class. Object class has a constructor with no parameters. Therefore, the statement super() inside the child class constructor calls the constructor of Object.

When we create an object of subclass, all parent class constructor gets called, up to topmost class Object. Thus, JVM executes constructors in the reverse order, from top to bottom. We call this process as constructor chaining in Java.