【发布时间】:2014-07-01 17:16:03
【问题描述】:
当我尝试在构造函数中创建具有自引用的对象时,我收到了 StackOverflowError。
public class Example1 {
private int i;
private Example1 zero;
public Example1(int i) {
super();
if (i > 0) {
this.i = i;
} else {
this.i = this.zero.i;
}
this.zero = new Example1(i);
}
public int getI() {
return i;
}
但是当我使用静态引用时不会发生错误。
public class Example2 {
private int i;
private static final Example2 ZERO = new Example2(0);
public Example2() {
this(ZERO.i);
}
public Example2(int i) {
super();
this.i = i;
}
public int getI() {
return i;
}
由于静态对象将在加载类时被初始化,所以我能够理解它正在工作。
但是在对象创建过程中发生了什么,谁能详细解释一下?
【问题讨论】:
-
两个代码一样吗?我猜没有。
-
Example2(int)不会自称自己,而Example1(int)会不断自称 -
至少该错误适用于该站点。但是递归是你的敌人。
-
为什么投反对票我能知道原因吗?
标签: java static self-reference