Java 递归构造函数调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16458819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:01:21  来源:igfitidea点击:

Recursive Constructor Invocation

javarecursionconstructorthis

提问by Darsshan Nair

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);
    }
}

This code shows an error which is:

此代码显示一个错误,即:

Recursive constructor invocation LecturerInfo()

递归构造函数调用 LecturerInfo()

Is it because of the no-argument constructor having conflicts with the constructor with parameters?

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

回答by Ankit

the code below is recursive. Since this()will call no arg constructor of current class that means LectureInfo()again.

下面的代码是递归的。因为this()LectureInfo()再次调用当前类的 no arg 构造函数。

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

回答by stinepike

by calling this()you are calling your own constructor. By observing your code it seems you were supposed to call super()instead of this();

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

回答by Sam

if you modify the fist constructor to this:

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

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

this will be recursive.

这将是递归的。