How can constructor chaining be done using this keyword in Java?

Constructor chaining enables us to call one constructor from another constructor of the class with respect to the current class object. We can use this keyword to perform constructor chaining within the same class. Consider the following example which illustrates how can we use this keyword to achieve constructor chaining.

  1. public class Employee
  2. {
  3.     int id,age;
  4.     String name, address;
  5.     public Employee (int age)
  6.     {
  7.         this.age = age;
  8.     }
  9.     public Employee(int id, int age)
  10.     {
  11.         this(age);
  12.         this.id = id;
  13.     }
  14.     public Employee(int id, int age, String name, String address)
  15.     {
  16.         this(id, age);
  17.         this.name = name;
  18.         this.address = address;
  19.     }
  20.     public static void main (String args[])
  21.     {
  22.         Employee emp = new Employee(10522“Vikas”“Delhi”);
  23.         System.out.println(“ID: “+emp.id+” Name:”+emp.name+” age:”+emp.age+” address: “+emp.address);
  24.     }
  25. }

Output

ID: 105 Name:Vikas age:22 address: Delhi