izac89
izac89

Reputation: 3940

Why is there a StackOverflowError in the following Java code?

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

Answers (5)

75inchpianist
75inchpianist

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

rgettman
rgettman

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

Jack
Jack

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

zw324
zw324

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

eidsonator
eidsonator

Reputation: 1325

You are calling new Classa() from inside your Classa constructor.

Upvotes: 1

Related Questions