Search code examples
javaconstructorstack-overflow

Java - instantiating objects of same class in its constructor


Why instantiating objects of same class within its constructor throws StackOverflowError? For instance ,

public class A {
    public A () {
        A a = new A() 
    }
}

will throw StackOverFlowError ?


Solution

  • It's exactly the same as with any other function unconditionally calling itself with exactly the same parameters:

    public void f() {
      f(); // <---- will cause a stack overflow due to infinite recursion
    }
    

    The function just keeps calling itself, and each invocation requires stack space. Sooner or later the stack is exhausted, and you get an exception.

    Exactly the same thing happens when A() keeps calling itself (in new A()).