[英]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.
在这个例子中,我想检查何时发生 StackOverflow 错误。 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.因此,当您创建
StackOverFlowSampleMain
实例时,它所做的第一件事就是初始化其oomeSampleMain
成员。 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.反过来,它会尝试初始化自己的
oomeSampleMain
成员,依此类推,直到程序因StackOverflowError
崩溃,因此从未达到x
的递增。
If you want to measure when the StackOverflowError
occurs, you could move the code that causes it to the end of the constructor:如果要测量
StackOverflowError
何时发生,可以将导致它的代码移动到构造函数的末尾:
public class StackOverFlowSampleMain {
StackOverFlowSampleMain oomeSampleMain;
static int x = 0;
StackOverFlowSampleMain() {
x++;
System.out.println(x);
oomeSampleMain = new StackOverFlowSampleMain(); // Here, after x is printed
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.