Calling a constructor from the another constructor of same class is known as Constructor chaining. We will understand this with the help of below program.
Example Program
In the below example the class “ChainingDemo” has 4 constructors and we are calling one constructor from another using this() statement. For e.g. in order to call a constructor with single string argument we have supplied a string in this() statement like this(“hello”).
Note: this() should always be the first statement in constructor otherwise you will get the below error message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Constructor call must be the first statement in a constructor
Complete Code:
package beginnersbook.com; public class ChainingDemo { //default constructor of the class public ChainingDemo(){ System.out.println("Default constructor"); } public ChainingDemo(String str){ this(); System.out.println("Parametrized constructor with single param"); } public ChainingDemo(String str, int num){ //It will call the constructor with String argument this("Hello"); System.out.println("Parametrized constructor with double args"); } public ChainingDemo(int num1, int num2, int num3){ // It will call the constructor with (String, integer) arguments this("Hello", 2); System.out.println("Parametrized constructor with three args"); } public static void main(String args[]){ //Creating an object using Constructor with 3 int arguments ChainingDemo obj = new ChainingDemo(5,5,15); } }
Output:
Default constructor Parametrized constructor with single param Parametrized constructor with double args Parametrized constructor with three args