gpt4 book ai didi

由于递归构造函数调用导致java堆栈溢出

转载 作者:行者123 更新时间:2023-11-29 03:22:20 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com