java 递归构造函数调用

vxf3dgd4  于 2023-01-04  发布在  Java
关注(0)|答案(4)|浏览(156)
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);
    }
}

此代码显示以下错误:
递归构造函数调用LecturrInfo()
是因为无参数构造函数与带参数构造函数冲突吗?

fykwrbwg

fykwrbwg1#

下面的代码是递归的。2因为this()不会调用当前类的arg构造函数,所以也是LectureInfo()

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

cnh2zyt32#

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

qqrboqgw

qqrboqgw3#

如果你把第一个构造函数修改为:

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

这将是递归的。

zaqlnxep

zaqlnxep4#

而不是这样:

public LecturerInfo()
          {
              this(); //Here you're invoking the default constructor inside default constructor, which is constructor recursion, which is not allowed.  
              this.Name = null;
              this.Address = null;
              this.salary=(float) 0.0;
          }

试试这个:在默认构造函数中调用参数化构造函数。

public LecturerInfo()
          {
              this("null","null",0.0f);
          }

相关问题