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.
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
public class testing {
testing t=new testing();
//
}
While creating first instance it will create new Instance by 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
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.