Search code examples
javaconstructorinner-classesouter-classes

Outerclass with its innerclass as an argument for the outerclass constructor


Im wondering if it is possible to create this object based on the code below or is it a cyclic dependency which cant be solved?

public class A {
  private B b;

  public A(B b) {
    this.b = b;
  }

  public class B {
    public B() {}
  }
  
}

I was provided with a class which looked like this and I cant find a way to initialize B or A. Its like and impossible cycle.


Solution

  • If all you do with instance of B in A's constructor is an assignment, then you could try using null at instantiation and then hand it a B instance:

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

    the above requires a.b to be public, or you need to add a setter. But that looks bad to me, so perhaps you should make B class static, and by doing so it can be instantiated independently of A::

    public class A {
        private B b;
    
        public A(B b) {
            this.b = b;
        }
    
        public static class B {
            public B() {}
        }
    }
    

    and then

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