构造函数链接。为什么要在this()中初始化参数

时间:2018-09-02 19:50:00

标签: java

我下面有一个课程。我有一个问题:为什么要在此初始化第三个参数(名称,sal,“古尔冈”);在第三个构造函数public Employee1(String name,int sal)中?我的意思是为什么我不能放“ addr”而不是初始化第三个参数-> this(name,sal,addr); ?

public class Employee1 {
    public String name;
    public int salary;
    public String address;

    //default constructor of the class
    public Employee1()
    {
        //this will call the constructor with String param
        this("Chaitanya");
        System.out.println("Default");
    }

    public Employee1(String name)
    {
        //call the constructor with (String, int) param
        this(name, 120035);
        System.out.println(name);
    }
    public Employee1(String name, int sal)
    {
        //call the constructor with (String, int, String) param
        this(name, sal, "Gurgaon");
        System.out.println(name + " " + sal);
    }
    public Employee1(String name, int sal, String addr)
    {
        this.name=name;
        this.salary=sal;
        this.address=addr;
        System.out.println(name + " "+ sal + " " + addr);
    }

    public static void main(String[] args)
    {
        Employee1 obj = new Employee1();
    }
}

1 个答案:

答案 0 :(得分:0)

如果不使用地址作为参数调用最后一个构造函数,那么倒数第二个构造函数将如下所示:

  public Employee1(String name, int sal)
  {
    //call the constructor with (String, int, String) param
    this.address = "Gurgaon";
    System.out.println(name + " "+ sal + " " + address);
  }

如果地址未在此处初始化,则地址将被打印为空。因此,就像上面的评论中提到的那样,您不必调用最终的构造函数,或者如果您不想的话,甚至不需要一个。