Babak
Babak

Reputation: 1

Java mutual dependency with interfaces set in constructor

I have 2 classes that rely on each other and they both have their respective interfaces. However, I cannot setup the constructor on both classes cleanly. In short, one class needs to be instantiated before the other class gets instantiated.

Class A implements IA {
    public A(IB b) {
        myBclass = b;
    }
    private IB myBclass;
}

Class B implements IB {
    public B(IA a) {
        myAclass = a;
    }
    private IA myAclass;
}

static void main(String[] args) {
    A a = new A(null);
    B b = new B(a);
    a.setB(b); // how can I avoid doing this
}

I would like to avoid setting member variables outside the constructor.

Upvotes: 0

Views: 110

Answers (1)

khelwood
khelwood

Reputation: 59112

You can have one construct the other.

class A implements IA {
    private IB myBclass;
    public A() {
        myBclass = new B(this);
    }
    // etc.
}
class B implements IB {
    private IA myAclass;
    public B(IA a){
        myAclass = a;
    }
    // etc.
}

That way you don't have to alter them after construction.

public static void main(String[] args){
    A a = new A();
    B b = a.getB();
}

Upvotes: 2

Related Questions