2 classes with a parameter in its constructor of another class

Lets say that I have class A and class B. Their constructor looks like this:

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

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

Both of them have an instance of another class as an instance variable.

Is it possible to instantiate these classes without an instancevariable value of null? I want an instance of class A and an instance of class B. An instance of class A should add an instance of class B as its instance variable and vice versa.

+4
source share
2 answers

One of the classes, let’s choose A, we need a method

public void setB(B b) {
    this.b = b;
}

which is called after Aand Bobjects.

+2
source

. , , . , , , setter,

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

class B {
    private A a;
    void setA(A a) { this.a = a; }
}
B b = new B();
A a = new A(b);
b.setA(a);
0

Source: https://habr.com/ru/post/1695596/


All Articles