递归构造函数调用

问题描述 投票:2回答:3
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()

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

java recursion constructor this
3个回答
13
投票

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

public LecturerInfo()
{
    this(); //here it translates to LectureInfo() 
    this.Name = null;
    this.Address = null;
    this.salary=(float) 0.0;
}

2
投票

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


1
投票

如果您将fist构造函数修改为此:

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

这将是递归的。

© www.soinside.com 2019 - 2024. All rights reserved.