Circular dependency in Java constructors

The constructor of your class A calls the constructor of class B. The constructor of class B calls the constructor of class A. You have an infinite recursion call, that’s why you end up having a StackOverflowError.

Java supports having circular dependencies between classes, the problem here is only related to constructors calling each others.

You can try with something like:

A a = new A();
B b = new B();

a.setB(b);
b.setA(a);

Leave a Comment