Reputation: 3940
Given the following code:
public class Classa {
int x=10;
void func(){
}
Classa inner=new Classa(){
void func(){
x=90;
}
};
public static void main(String[] args) {
Classa c=new Classa();
c.inner.func();
}
}
Why does my app crashes during instantiating? (accourding to debugger) It goes into some kind of infinite recursive. Any idea?
Upvotes: 4
Views: 96
Reputation: 4102
You are calling new Classa(). This triggers the class to construct.
Think now, how does the inner
variable get instantiated? On the constructor call, it recursively calls inner = new Classa()
So now what happens from that call? The process recursively repeats until you get your stack overflow
Upvotes: 2
Reputation: 178333
You have an instance variable inner
that is defined in your class. You are initializing it to an anonymous subclass of Classa
. This will create another instance of Classa
. But that new instance will attempt to create its own inner
, resulting in an infinite loop of calls to creating an instance of Classa
. Each call places things on the stack, and eventually a StackOverflowError
results.
One way to stop it would be to make inner
static
, so there is only one inner
for the entire class:
static Classa inner = new Classa(){
Upvotes: 1
Reputation: 133629
Because you have
Classa inner=new Classa()
which is equivalent to
class Classa {
Classa inner;
Classa() {
inner = new Classa();
}
}
which keeps instantiating an inner variable which is of the same type of the containing class, thus creating an infinite amount of instances.
To initialise a Classa
instance you need to allocate the inner variable which is of Classa
type, here it is the infinite recursion.
Upvotes: 3
Reputation: 27210
While you are trying to construct a new Classa
object, the instance variable inner
gets initialized as part of the construction process, which caused another call to the Classa
constructor, thus the code gets into a endless recursion.
Upvotes: 1
Reputation: 1325
You are calling new Classa()
from inside your Classa constructor.
Upvotes: 1