递归构造函数调用

时间:2013-05-09 09:43:09

标签: java recursion constructor this

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()

是否因为无参数构造函数与带参数的构造函数冲突?

3 个答案:

答案 0 :(得分:12)

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

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

答案 1 :(得分:2)

通过调用this()调用自己的构造函数。通过观察您的代码,您似乎应该调用super()而不是this();

答案 2 :(得分:1)

如果您将第一个构造函数修改为:

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

这将是递归的。