Reputation: 17580
I am sure that, this ques code must be asked in this site. But I am not able to search, This is basic ques, but I am not getting it because of my poor basic concept-
public class A {
A obj = new A();
public static void main(String arg[])
{
A ob = new A();
}
}
It is giving java.lang.StackOverflowError
,Why?
Upvotes: 0
Views: 520
Reputation: 528
Every time you create an object A
it will create another object A
that will create another object A
...
Upvotes: 5
Reputation: 11486
StackOverflow errors occur because there is a very deep recursion within the application. When you instantiate A
, you also call the same constructor to create another instance of A
and hence, you have a recursive tree and thus causing the stack overflow error.
Hence, the real problem is deep recursive calls to instantiate A
.
Upvotes: 1
Reputation: 326
When you create object of type A, you're creating new object of type A, which creates new object of type A etc.
Upvotes: 0
Reputation: 213223
Your class is essentially equivalent to:
public class A {
A obj;
public A() {
obj = new A();
}
public static void main(String arg[]) {
A ob = new A();
}
}
Now you see how you got that error? Everytime you create an instance of A
, the constructor get's called, which again invokes itself to create another instance, and this goes on filling up the stack till it overflows.
Upvotes: 5