易百教程

56、如何使用 this 关键字完成构造函数链接?

构造函数链接使我们能够从该类的另一个构造函数中调用一个构造函数,该构造函数与当前类对象有关。 可以使用this关键字在同一个类中执行构造函数链接。 考虑以下示例,该示例说明了我们如何使用 this 关键字来实现构造函数链接。

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", "Yiibai");  
        System.out.println("ID: "+emp.id+" Name:"+emp.name+" age:"+emp.age+" address: "+emp.address);  
    }  

}

运行结果:

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