Har*_*ran 1 java static self-reference
当我尝试在构造函数中创建具有自引用的对象时,我得到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;
}
Run Code Online (Sandbox Code Playgroud)
但是,当我使用静态引用时,不会发生错误.
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;
}
Run Code Online (Sandbox Code Playgroud)
由于静态对象将在加载类时初始化,因此我能够理解它的工作原理.
但是在对象创建过程中发生了什么,有谁能详细解释一下?