Consider following 2 programs giving same error
First calss:
public class Testing {
Testing t=new Testing();
public static void main(String args[]){
testing t1=new testing();
}
}
Second class:
class foo{
void baz(){
new testing();
}
}
public class testing {
testing t=new testing();
public static void main(String args[]){
foo f=new foo();
f.baz();
}
}
how does above code giving following error?
I know instance of class is creating recursively but I want to know how?
Exception in thread "main" java.lang.StackOverflowError
at com.Testing.<init>(Testing.java:4)
at com.Testing.<init>(Testing.java:4)
also Why doesn’t this happen if we do
public class testing {
testing t2=new testing();
testing t1=new testing();
public static void main(String args[])
{//anything}
}
as t1 will require t2 object to be initalized and vice-versa?
This is the problem:
This is broadly the same as:
That makes the recursion clearer – the constructor is unconditionally calling itself.
Each instance of
Testingcontains a reference to another instance ofTesting. That needn’t be a problem – but it is here, because it’s creating a new instance ofTesting. So creating the “outermost” instance immediately triggers the creation of another one… which triggers the creating of another one, etc.Your two classes aren’t significantly different in that respect – creating any instance of
Testingwill cause a stack overflow.EDIT: Regarding this code (names and formatting improved):
will still throw the same exception if you try to create an instance of
Testing. You’re wrong to state that “t1 will require t2 object to be initialized” though – there’s no interdependence between the variables here. Each variable initializer creates a separate object… but each of those objects would in turn try to create two more instances ofTesting.Note that an instance of
Testingis not required in order to run themainmethod – but if thatmainmethod either callsnew Testingdirectly, or calls something else which callsnew Testing(), then you’ll get the stack overflow.