[Solved] Initialization of anonymous inner class member variable causes java.lang.stackoverflowerror

Project scenario:

An abstract class A in Java needs to initialize a member variable of the same type anonymously,

public class Main {
  public static void main(String[] args) {
    new B();
  }

}

abstract class A {
   A a = new A() {//Member variables of the same type
     @Override
     void do_sth() {
       System.out.println("do nothing");
     }
   };
  abstract void do_sth();
}

class B extends A{

  @Override
  void do_sth() {
	System.out.println("doing B");
  }
}

Problem Description:

Java.lang.stackoverflowerror directly overflowed the stack


Cause analysis:

When creating object B, the anonymous inner class in object a is also created, and the inner class creates its own inner class, resulting in infinite recursion.


Solution:

Try not to use anonymous inner classes as member variables. If you want to use them, be sure to pay attention to whether they contain the possibility of infinite recursion.

Read More: