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 application crash during instance creation? (load on the debugger) It goes into some kind of infinite recursive. Any idea?

+4
source share
5 answers

You call the new Classa (). This causes the class to be created.

Think about how to get an instance of the variable inner ? In a constructor call, it recursively calls inner = new Classa()

So what happens after this call? The process recursively repeats until you get a stack overflow

+2
source

Since you have

 Classa inner=new Classa() 

which is equivalent

 class Classa { Classa inner; Classa() { inner = new Classa(); } } 

which stores an instance of an internal variable that has the same type of the containing class, thereby creating an infinite number of instances.

To initialize an instance of Classa , you need to allocate an internal variable of type Classa , here it is infinite recursion.

+3
source

You call new Classa() from your Classa constructor.

+1
source

While you are trying to create a new Classa object, the inner instance variable is initialized as part of the build process, which has caused another call to the Classa constructor, so the code gets into infinite recursion.

+1
source

You have an inner instance variable that is defined in your class. You initialize it with an anonymous subclass of Classa . This will create another instance of Classa . But this new instance will try to create its own inner , which will lead to an endless loop of Classa instance creation calls. Each call puts things on the stack, and the result is a StackOverflowError .

One way to stop this is to make inner static , so there is only one inner for the whole class:

 static Classa inner = new Classa(){ 
+1
source

Source: https://habr.com/ru/post/1479419/


All Articles