Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass a self-reference to constructors in java?

i have a class A that needs to instantiate a second class B, whose constructor needs a reference to the same object of class A...

would look like:

public class A {
    B b;

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

public class B {
    A a;

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

well - eclipse keeps complaining that this isnt possible. i assume, this is because the reference of class A isnt "ready" yet at this moment...? but the error wont go away if i move the init of class B to a seperate function within A wich i would call from "outside"...

how can i pass this self-reference from outside to the constructor of B?

like image 640
xenonite Avatar asked Jan 20 '26 14:01

xenonite


2 Answers

Be very careful, because until A is constructed, it doesn't really exist. If B were to call a method on A, the program should fail because you can't call a method on A prior to A being constructed. Construction is not complete until A fully returns from its constructor code.

If you must initialize B with A whenever A is constructed, it is much better to make a factory class for A which guarantees that B is initialized after A is constructed. It would look something like this

public class AFactory {

  public A newA() {
    A a = new A();
    B b = new B(a);
    return a;
  }

}

For this to work properly 100%, you might need to limit the visibility of the A() constructor. I personally would put AFactory into the same package as A and make the access "default" or "package private like so

package same.as.afactory;

public class A {
  A() {
    ...
  }
}
like image 200
Edwin Buck Avatar answered Jan 22 '26 08:01

Edwin Buck


I'd ask myself: Are you sure that's the design you want? And, if it is, would it make sense for one of those classes to be an inner class of the other?

like image 26
Amadan Avatar answered Jan 22 '26 06:01

Amadan