【发布时间】:2019-07-20 11:26:33
【问题描述】:
想不出更好的标题。
经典学习示例:Human 类,其中属性为姓名、年龄、母亲和父亲。父母都是Human。
public class Human {
String name;
int age;
Human mother;
}
我想创建 3 个构造函数:
-
Human(); -
Human(String name, int age); -
Human(String name, int age, Human mother)。
我猜我确实了解链接的工作原理,这就是我所做的:
Human() {
this("Jack", 22);
}
Human(int age, String name) {
this(age, name, new Human()); // new Human() will cause SOF Error.
}
Human(int age, String name, Human mother) {
this.age = age;
this.name = name;
this.mother = mother;
}
如上所述,我收到了StackOverflowError,我再次猜我知道为什么会这样了。 虽然公平地说,我想我会得到像人类杰克这样的东西,他的母亲也是人类杰克。
不过,我想知道该怎么做。我的猜测是,我应该使用所有参数调用构造函数,而不是 new Human(),但我不确定它是否正确以及唯一可用的选项。
将不胜感激这里的任何指导。
【问题讨论】:
-
new Human()调用this("Jack", 22)然后调用new Human(age, name)然后再次调用new Human()。因此,Stackoverflow。 -
人类拥有默认值真的有意义吗?
标签: java constructor-overloading constructor-chaining