How to properly initialize the Solution.C class constructor?

class Solution{ class A(B b){ private B b; A(){ this.b=b; } } class B{ private A a; B(A a){ this.a=a; } } class C{ C(){ A a=new //... B b=new //... } } } 
  • Don't do that. The presence of cyclic dependencies in the code is a sure sign of the wrong architecture and a clear symptom for refactoring. - falstaf
  • one
    It is impossible to reason "right / wrong" apart from the semantics of classes. And it is impossible to talk about semantics with the names A , B , C Give real semantics, real class names. - VladD

1 answer 1

If it is necessary that classes A and B store references to each other, then these links can be passed not as arguments to the constructors, but as the values ​​of the corresponding properties, i.e.

 class A{ private B b; A(){ //код конструктора } public void setB(B b){ this.b = b; } } public B getB(){ return b; } 

and also for class B.

for class C:

 public class C{ C(){ A a = new A(new B()); B b = a.getB(); }