Constructor Chaining Java Example Program


Definition

Constructor chaining is calling a constructor from the another constructor of the same class.

Chaining Constructor Characteristics In Java

  • Call another constructor using this() keyword in the same class.
  • The class has two or more constructors.
  • Each constructor has various type of arguments.

Syntax

class ClassName{

    public ClassName() {
        //Do Something
    }

    public ClassName(String string) {
        //Calling the Constructor without any parameters - Chaining
        this();
        //Do something
    }
}

Constructor Chaining Example Program

public class ConstructorChaining {
    public static void main(String[] args) {
        ChainingClass object = new ChainingClass("This is the third ", "Chaining Constructor");
    }
}

class ChainingClass{

    public ChainingClass() {
        System.out.println("This is the first Chaining Constructor");
    }

    public ChainingClass(String string) {
        //Calling the Constructor without any parameters
        this();
        System.out.println(string);
    }
    
     public ChainingClass(String string1, String string2) {
         //Calling the constructor with one parameter - Chaining
         this("This is the second Chaining Constructor");
         System.out.println(string1+string2);
    }
}

Sample Output

This is the first Chaining Constructor
This is the second Chaining Constructor
This is the third Chaining Constructor