gpt4 book ai didi

java - 以下java程序中的stackoverflow错误

转载 作者:搜寻专家 更新时间:2023-11-01 04:04:44 24 4
gpt4 key购买 nike

public class testing {    
testing t=new testing();

public static void main(String args[]){
testing t1=new testing();
t1.fun();
}

void fun(){
int a=2;
int b=t.fun2(a);
System.out.println(a+" "+b);
}

int fun2(int a)
{
a=3;
return a;
}
}

为什么上面的代码给出以下错误?我只想知道原因,因为在这种情况下很难预料到 StackOverFlowError 错误。

Exception in thread "main" java.lang.StackOverflowError
at com.testing.<init>(testing.java:4)
at com.testing.<init>(testing.java:4)

最佳答案

您正在递归创建 testing 的实例

public class testing {    
testing t=new testing();
//

}

在创建第一个实例时,它将通过 testing t=new testing(); 创建新实例,这将再次创建新实例,依此类推

关于java - 以下java程序中的stackoverflow错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11219968/

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