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:
- Abstract method and static method of java interface
- Java callback function implementation case
- Explicit and implicit conversion of Java data type
- Java error prompt….. cannot be resolved
- [Solved] asList().add() error: UnsupportedOperationException
- Java error: unable to find or load main class (package name in source file)
- Initializingbean Interface & Applicationcontextaware Interface in Springboot
- Java — for loop printing graphics (loop structure)
- How to Solve JUnit Debugging initializationerror ERROR
- How to Solve JVM Common Errors: outofmemoryerror & stackoverflowerror
- Flink Error: is not serializable. The object probably contains or references non serializable fields.
- [Solved] error: method does not override or implement a method from a supertype
- Asynchronous callback case of Java callback function
- Java: How to Find the Minimum Value from a Random Array by Bubble Sort Method
- [Solved] Log Error: NAN OR INFINITY
- How to Solve Junit Unit Test Error: “No runnable methods“
- Ternary operator in Java?: error: not a statement
- Java Error: No enclosing instance of type Main is accessible. Must qualify the allocation with an encl
- Java uses single thread pool to realize multi thread sequential execution (non alternating, non synchronous)
- CreateProcess error = 5, access denied. [How to Solve]