Constructor Chaining in Java | Example Program

Constructor chaining in Java is a technique of calling one constructor from within another constructor by using this and super keywords.

The keyword “this” is used to call a constructor from within another constructor in the same class.

The keyword “super” is used to call the parent (super) class constructor from within child (subclass) class constructor. It occurs through inheritance.

We cannot call the constructor directly by name because it is illegal in Java.

When we use constructor chaining technique in Java programming, it is important to understand the order in which the constructor will execute.

When we create an object of a subclass, the subclass constructor first calls its superclass constructor before performing its own tasks.

If the superclass is derived from another class, the superclass constructor calls its superclass constructor before performing its own tasks.

This process continues until it reaches the last chained constructor and the end of the chain will always object class constructor. This is because every class is inherited from Object class by default. This is called constructor chaining in java.

That means if we create an object of subclass, all its superclasses are also instantiated.

To understand the constructor chaining process, look at the below figure. In this figure, a class “College” contains three constructors default, one parameter, and two parameters.

When an object of class College is created by passing two arguments to its constructor, it will immediately call two parameters constructor.

The keyword this(name) calls one parameter constructor from within two parameters constructor and then this() calls default constructor. That’s the order of execution.

You can also change the order as you like. Thus, it is important to understand the order of execution of the constructor in Java program that which constructor has to execute first and last?

Constructor chaining in java

Why do we use/need Constructor chaining in Java?


In Java programming, constructor chaining is used where we want to perform multiple tasks in a separate constructor for each task and make their order by chaining. This technique makes the program more readable and easy to understand for everyone.


We can provide as many constructors as we want within the class and use constructor chaining to set the link among them.

How to call one constructor from another constructor in Java?


To call one constructor from another constructor is called constructor chaining in java. This process can be implemented in two ways:

  • Using this() keyword to call the current class constructor within the “same class”.
  • Using super() keyword to call the super class constructor from the “base class”.

Let’s understand the concept with the help of example programs one by one.

Current Class Constructor Call in Java with Example Program


If we need to call the same or current class constructor within the same class, we will have to use this() Keyword. The syntax to call the same class constructor is as follows:
Syntax:

this(), or this(ParamterList)

The statement this(parameters) 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 String argument.
  • this(“shubh”, 24)  ➨ To call two parameters current class constructor with String and int argument.

Note:

1. We must use this () keyword to call the current class constructor because JVM never puts automatically this() keyword like a super() keyword.

Java constructor chaining using super and this keyword

2. this() keyword must be in the first line of the constructor to call the same or current class constructor. Otherwise java compiler will generate this error message: Exception in thread “main” java.lang.Error: Unresolved compilation problem: Constructor call must be the first statement in the constructor.


3. There must be at least one constructor without this keyword.
4. Java Constructor chaining can be done in any order.

Let’s take an example program where we will create constructor chaining. We will call the current class constructor using this keyword. Look at the program source code and follows all steps explained in the coding.

Program source code 1:

package constructorProgram; 
public class Developed 
{ 
  Developed() 
  { 
     System.out.println("Java was developed by James Gosling"); 
  } 
Developed(int year) 
{ 
// Declaration of this keyword with two parameters list. 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."); 
  } 
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"); 
 } 
// Instance method declaration. 
    void display() 
    { 
       System.out.println("The Java compiler is written in Java but Java runtime in ANSI C."); 
    } 
// Static method or main method. 
    public static void main(String[] args) 
    { 
// Create the object of class Developed using the new keyword and passes the int value. 
     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. So, the control of execution will be transferred to one parameter constructor.

2. From inside one parameter constructor, 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, this() will call default constructor. After the complete execution of default 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.

Let’s take another example program based on the above points. In this example program, we will define default constructor and two parameterized constructors.

We will call constructors using this keyword from within another class. Look at the program source code.

Program source code 2:

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) 
{ 
//Create three objects of classes with passing different parameters to their constructors. 
     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

Super Class Constructor Call in Java with Example Program


If we need to call superclass constructor from the subclass constructor then we will have to use the super() keyword in the subclass constructor. The syntax to call a superclass constructor is as follows:
Syntax:

super(), or super(Parameter_list);

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.

1. We must use the super() keyword to call the superclass constructor but if you do not put a super keyword, JVM will put automatically the super() keyword.

2. The super() keyword must be in the first line of the constructor. Calling a superclass constructor’ name in a subclass causes a syntax error.

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

Let’s take an example program where we will use both this and super keywords to call current class and superclass constructors.

Program source code 3:

package constructorProgram; 
 public class School 
 { 
// Declare instance variables. 
    String stName; 
    int stRoll; 
    int stId; 
School(String schoolName) 
{ 
 this(2); // Calling one parameter current class constructor with passing integer value within the same class. 
 System.out.println("Student's Detail: "); 
} 
School(int s) 
{ 
  System.out.println("Delhi Public School"); 
} 
School(String stName, int stRoll, int stId) 
{ 
  this("DPS");// Calling one parameter current class constrcutor with passing String argument within same class. 
  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

Program source code 4:

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. 
 // JVM will automatically put the super() keyword and call 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

Hope that this tutorial has covered almost all the important points related to constructor chaining in java with example programs. I hope that you will have understood this simple topic.

Please, share this tutorial on social networking sites with your friends if you like this.
Thanks for reading!!!
Next ⇒ Copy Constructor in Java
⇐ PrevNext ⇒

Leave a Comment