0

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.

freeze
  • 13
  • 1

1 Answers1

1

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);
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
  • Let's definitely highlight: __This is really bad code, and the first snippet is a horrible idea, it just proves a point, like a silly riddle, that you CAN do it__. The second snippet (make it `static`) is what you should be doing. – rzwitserloot May 05 '23 at 00:26
  • That's absolutely correct. There's also a high chance that the best approach would simply be refactoring that code and make it stink less. – Marcin Orlowski May 05 '23 at 00:30