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:
- [Solved] Hibernate Error: java.lang.StackOverflowError at java.lang.Integer.toString(Integer.java:402)
- Java.lang.stackoverflowerror error [How to Solve]
- [Solved] Method threw ‘java.lang.StackOverflowError‘ exception. Cannot evaluate
- nested exception is java.lang.StackOverflowError [How to Solve]
- [Solved] IDEA startup Error: Java lang.StackOverflowError
- Lotti triggered Java lang.StackOverflowError [How to Solve]
- Java uses class array to report error Exception in thread “main” java.lang.NullPointerException solution
- [Solved] JAVA Error: Error occurred during initialization of boot layer java.lang.module.FindException
- [Solved] Java.lang.BootstrapMethodError: call site initialization exception
- [Solved] Hbase-shell 2.x Error: Unhandled Java exception: java.lang.IncompatibleClassChangeError: Found class jline.Terminal…
- java: java.lang.IllegalAccessError: class lombok.javac.apt.LombokProcessor (in unnamed module @0x590
- [Solved] Mapreducer Class Conversion error: java.lang.ClassCastException
- [Solved] Java.lang.ClassCastException: [Ljava.lang.Long; cannot be cast to java.util.List
- [Solved] Jenkins Publish to rancher Error: ERROR: Build step failed with exception java.lang.ClassCastException: class com.
- [JVM] stack overflow error stackoverflowerror [How to Solve]
- [Solved] nacos Startup Error: nested exception is java.lang.RuntimeException: java.lang.RuntimeException: [db-load-error
- Java error: java.lang.NoSuchMethodError
- [Solved] Java 9 reflection error: java.lang.reflect.InaccessibleObjectException
- How to Solve JVM Common Errors: outofmemoryerror & stackoverflowerror
- [Solved] Java.lang.IllegalStateException: getReader() has already been called for this request