Search code examples
javaconstructorreferenceinstances

Java: how to create instances of two different classes in a third class and pass references to each other through the constructors


This is more of a theoretical question. Suppose I have 3 classes A, B and C. What I want to do is this:

public class A {
  B b = new B(c);
  C c = new C(b);
}

public class B {
  public B(C c) {

  }
}

public class C {
  public C(B b) {

  }
}

I know this code wont work. So, is there another way to do it?


Solution

  • You are correct, you can't do this. Something else that is unsafe as well so DO NOT DO THIS is:

    public class A {
      B b = new B(this);
      C c = new C(this);
    }
    
    public class B {
      public B(A a) {
    
      }
    }
    
    public class C {
      public C(A a) {
    
      }
    }
    

    This sort of circular dependency can only be resolved by using a setter method to initialize either B or C after the other one has been created.

    However the very fact you need to do this suggests to me that there is an architectural problem here, these classes are far too tightly coupled and you really need to think about design.