Search code examples
javastack-overflow

Why does StackOverflowError occur in the below scenario?


public class B {

    public static void main(String[] args) {
        A a = new A();
    }
}

public class A {

    A b = new A();
}

Solution

  • Because every A creates an inner field named b of type A. That's infinitely recurisve, because to create a b you must also create an A (which adds another b). Because initializers are copied to the default constructor, your example is equivalent to something like,

    public class A {
       // A b=new A(); 
       A b;
       public A() {
           super();
           b = new A();
       }
    }