简体   繁体   中英

When an instance of a class is created in itself, then why the statements in the constructor are not executed?

When a class is instantiated, its constructor is called. In this example, I want to check when a StackOverflow error occurred. But the statements declared inside the constructor are not executed, why? see the following code

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();

    }
}

Member initialization happens before the constructor's body. So when you create a StackOverFlowSampleMain instance, the first thing it does is to initialize its oomeSampleMain member. It, in turn, attempts to initialize its own oomeSampleMain member, and so on, until the program crashes with a StackOverflowError , so the incrementing of x is just never reached.

If you want to measure when the StackOverflowError occurs, you could move the code that causes it to the end of the constructor:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM