递归调用构造函数(Recursive Constructor Invocation)

2019-09-02 08:47发布

public class LecturerInfo extends StaffInfo {

    private float salary;

    public LecturerInfo()
    {
        this();
        this.Name = null;
        this.Address = null;
        this.salary=(float) 0.0;
    }

    public LecturerInfo(String nama, String alamat, float gaji)
    {
        super(nama, alamat);
        Name = nama;
        Address = alamat;
        salary = gaji;
    }

    @Override
    public void displayInfo()
    {
         System.out.println("Name :" +Name);
         System.out.println("Address :" +Address);
         System.out.println("Salary :" +salary);
    }
}

此代码显示一个错误,其是:

递归构造函数调用LecturerInfo()

是不是因为其与参数的构造冲突的无参数的构造函数?

Answer 1:

下面的代码是递归的。 由于this()将调用当前类的无参数的构造函数,这意味着LectureInfo()一次。

public LecturerInfo()
{
    this(); //this is calling LectureInfo() 
    this.Name = null;
    this.Address = null;
    this.salary=(float) 0.0;
}


Answer 2:

通过调用this()你调用自己的构造函数。 通过观察你的代码看起来你应该调用super()而不是this();



Answer 3:

如果修改了拳头构造函数如下:

 public LecturerInfo()
 {
   this(null, null, (float)0.0);
 }

这将是递归的。



文章来源: Recursive Constructor Invocation