Search code examples
javastaticconstructorstack-overflow

StackOverFlow Error in Instantiating an Object


I'm reviewing for a certification exam and I experimented with the following codes:

class A {   
    B b = new B();
    static {
        System.out.println("A static.");
    }
    {
        System.out.println("A instance.");
    }
    A() {
        System.out.println("A constructor.");
    }
}
class B extends A {
    static {
        System.out.println("B static.");
    }
    {
        System.out.println("B instance.");
    }
    B() {
        System.out.println("B constructor.");
    }
}

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

It prints:

A static. B static.

and causes a stack overflow afterwards. I'm having a hard time understanding why. Would you be able to help me out?


Solution

  • A instantiates B. B happens to also be of type A, so that gets instantiated again. Which instantiates B... and so forth.