为什么我们无法在构造函数中创建非静态自引用对象

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)

由于静态对象将在加载类时初始化,因此我能够理解它的工作原理.

但是在对象创建过程中发生了什么,有谁能详细解释一下?

Flo*_*vic 12

Exampel1在构造函数中递归地创建新实例.

静态字段只会创建一次.这就是为什么示例1创建溢出而第二个不创建溢出的原因.