Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a StackOverflowError in the following Java code?

Tags:

java

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?

like image 414
izac89 Avatar asked Feb 16 '23 14:02

izac89


2 Answers

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.

like image 158
Jack Avatar answered Mar 16 '23 09:03

Jack


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

like image 31
75inchpianist Avatar answered Mar 16 '23 08:03

75inchpianist