我是 Java 编程的新手。今天这个例子是我的老师用非静态方法教的。任何人都从jvm架构的角度告诉我详细的答案
class Example {
int x = 10;
int y = 20;
Example e1 = new Example();
public static void main(String[] args){
System.out.println("main method start");
Example e2 = new Example();
System.out.println("main method end");
}
}
最佳答案
class Example {
int x = 10;
int y = 20;
Example e1 = new Example(); // this is the reason
当您在 main() 方法中调用 new Example 时,会发生什么情况,
Example e1=new Example();
正在执行。
在 Example e1=new Example();
中,您再次创建了 Example()
的新对象,它将再次调用 new Example()
(递归调用新的 Example()
导致 StackOverflowError
)。
关于由于递归构造函数调用导致java堆栈溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22879534/