StackOverFlowSampleMain

StackOverFlowSampleMain

实例化一个类时,将调用其构造函数。在此示例中,我想检查何时发生StackOverflow错误。但是构造函数内部声明的语句没有执行,为什么?
看下面的代码

public class StackOverFlowSampleMain {
    StackOverFlowSampleMain oomeSampleMain = new StackOverFlowSampleMain();
    static int x = 0;

    StackOverFlowSampleMain() {
        x++; //aren't these lines supposed to be executed?
        System.out.println(x);
    }

    public static void main(String[] args) {
        StackOverFlowSampleMain oomeSampleMain = new StackOverFlowSampleMain();

    }
}

最佳答案

成员初始化发生在构造函数的主体之前。
因此,当您创建一个StackOverFlowSampleMain实例时,它要做的第一件事就是初始化其oomeSampleMain成员。反过来,它尝试初始化自己的oomeSampleMain成员,依此类推,直到程序因StackOverflowError崩溃,因此,从未达到x的增量。

如果要测量StackOverflowError何时发生,可以将导致它的代码移到构造函数的末尾:

public class StackOverFlowSampleMain {
    StackOverFlowSampleMain oomeSampleMain;
    static int x = 0;

    StackOverFlowSampleMain() {
        x++;
        System.out.println(x);
        oomeSampleMain = new StackOverFlowSampleMain(); // Here, after x is printed
    }
}

10-06 02:12