Java递归构造函数调用

时间:2018-02-07 11:40:27

标签: java

public class Person {
    String name;
    int weight;
    int height;

    public Person(String name, int weight, int height){
        this.name=name;
        this.weight=weight;
        this.height=height;
    }

    public Person(String name, int weight){
        this(name, weight);
    }
}

错误:(12,12)java:递归构造函数调用

我应该更改什么来编译它而没有错误?

使用IntelliJ 2017.1

1 个答案:

答案 0 :(得分:5)

 public Person(String name, int weight){
        this(name, weight);
    }

是。这是递归的。调用相同的构造函数。

可能你想打电话给另一个

 public Person(String name, int weight){
        this(name, weight,0); // default height 0 
    }

this(name, weight,0);使用3个参数调用其他构造函数,并将高度传递为0,因为没有高度可用。或者您可以传递任何默认高度。

相关问题