当一个class的实例本身被创建时,为什么构造函数中的语句没有被执行?
When an instance of a class is created in itself, then why the statements in the constructor are not executed?
当 class 被实例化时,它的构造函数被调用。在此示例中,我想检查 Whosebug 错误何时发生。但是构造函数内部声明的语句并没有执行,为什么?
看下面代码
public class WhosebugSampleMain {
WhosebugSampleMain oomeSampleMain = new WhosebugSampleMain();
static int x = 0;
WhosebugSampleMain() {
x++; //aren't these lines supposed to be executed?
System.out.println(x);
}
public static void main(String[] args) {
WhosebugSampleMain oomeSampleMain = new WhosebugSampleMain();
}
}
成员初始化发生在构造函数的主体之前。
所以当你创建一个 WhosebugSampleMain
实例时,它做的第一件事就是初始化它的 oomeSampleMain
成员。反过来,它会尝试初始化自己的 oomeSampleMain
成员,依此类推,直到程序因 WhosebugError
而崩溃,因此从未达到 x
的递增。
如果您想测量 WhosebugError
何时发生,您可以将导致它的代码移动到构造函数的末尾:
public class WhosebugSampleMain {
WhosebugSampleMain oomeSampleMain;
static int x = 0;
WhosebugSampleMain() {
x++;
System.out.println(x);
oomeSampleMain = new WhosebugSampleMain(); // Here, after x is printed
}
}
当 class 被实例化时,它的构造函数被调用。在此示例中,我想检查 Whosebug 错误何时发生。但是构造函数内部声明的语句并没有执行,为什么? 看下面代码
public class WhosebugSampleMain {
WhosebugSampleMain oomeSampleMain = new WhosebugSampleMain();
static int x = 0;
WhosebugSampleMain() {
x++; //aren't these lines supposed to be executed?
System.out.println(x);
}
public static void main(String[] args) {
WhosebugSampleMain oomeSampleMain = new WhosebugSampleMain();
}
}
成员初始化发生在构造函数的主体之前。
所以当你创建一个 WhosebugSampleMain
实例时,它做的第一件事就是初始化它的 oomeSampleMain
成员。反过来,它会尝试初始化自己的 oomeSampleMain
成员,依此类推,直到程序因 WhosebugError
而崩溃,因此从未达到 x
的递增。
如果您想测量 WhosebugError
何时发生,您可以将导致它的代码移动到构造函数的末尾:
public class WhosebugSampleMain {
WhosebugSampleMain oomeSampleMain;
static int x = 0;
WhosebugSampleMain() {
x++;
System.out.println(x);
oomeSampleMain = new WhosebugSampleMain(); // Here, after x is printed
}
}