0 votes
in JAVA by
How can constructor chaining be done using this keyword?

1 Answer

0 votes
by
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

Related questions

0 votes
asked Mar 13, 2021 in PL/SQL by rajeshsharma
0 votes
asked Oct 11, 2020 in JAVA by SakshiSharma
...