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?
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
For this to work properly 100%, you might need to limit the visibility of the A() constructor. I personally would put
AFactoryinto the same package asAand make the access “default” or “package private like so