[英]stackoverflow error in following java program
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;
}
}
why does above code giving following error? 为什么上面的代码会出现以下错误? I just want to know the reason because it is difficult to expect StackOverFlowError
error in this case. 我只是想知道原因,因为在这种情况下很难期望StackOverFlowError
错误。
Exception in thread "main" java.lang.StackOverflowError
at com.testing.<init>(testing.java:4)
at com.testing.<init>(testing.java:4)
You are recursively creating instance of testing
您以递归方式创建testing
实例
public class testing {
testing t=new testing();
//
}
While creating first instance it will create new Instance by testing t=new testing();
在创建第一个实例时,它将通过testing t=new testing();
来创建新的实例testing t=new testing();
which will again create new instance and so on 这将再次创建新实例等
try this solution, 试试这个解决方案
public class testing {
public static void main(String args[]){
testing t1=new testing();
t1.fun(t1);
}
void fun(testing t1){
int a=2;
int b=t1.fun2(a);
System.out.println(a+" "+b);
}
int fun2(int a)
{
a=3;
return a;
}
}
You have to create field at class level but instantiate it once where in main 您必须在类级别创建字段,但在main中将其实例化一次
public class Testing {
static Testing t1;
public static void main(String args[]){
t1=new Testing();
t1.fun();
}
void fun(){
int a=2;
int b=t1.fun2(a);
System.out.println(a+" "+b);
}
int fun2(int a)
{
a=3;
return a;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.