How can constructor chaining be done using this keyword?

DWQA QuestionsCategory: JavaHow can constructor chaining be done using this keyword?
Editor Staff asked 10 months ago

How can constructor chaining be done using this keyword?

1 Answers
Editor Staff answered 10 months ago

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.
public class Employee
{
int id,age;
String name, address;
public Employee (int age)
{
this.age = age;
}
public Employee(int id, int age)
{
this(age);
this.id = id;
}
public Employee(int id, int age, String name, String address)
{
this(id, age);
this.name = name;
this.address = address;
}
public static void main (String args[])
{
Employee emp = new Employee(105, 22, “Vikas”, “Delhi”);
System.out.println(“ID: “+emp.id+” Name:”+emp.name+” age:”+emp.age+” address: “+emp.address);
}

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