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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With