There are many ways to deal with it, none of them ideal:
The deferred-construction approach:
B b = new B();
C c = new C();
b.setC(c);
c.setB(b); // until this point, initialization is not complete
The break-the-cycle approach:
B b = new B(); // B is not fully initialized until later
C c = new C(b);
b.setC(c); // everything set
The one-sets-the-other approach:
B b = new B(); // internally initializes its 'C' instance
C c = b.getC(); // uses the C instance set by B
// inside B
public B() {
c = new C(this); // leaking 'this' in constructor, not ideal
}
And then there is the Recommended Way (TM):
D d = new D(); // isolates what B needs from C and C needs from B
B b = new B(d);
C c = new C(d);
which is based on the observation that there is typically no need for B
and C
to depend fully on each other - you can take the common part and isolate it D
, and share that.