views:

74

answers:

3

hi there!

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?

A: 

Create a holder object which you can pass from A to B, and then insert the this instance of A into when the A constructor is finished. Then B can refer to the this-value inside the holder later.

Thorbjørn Ravn Andersen
+4  A: 

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?

Amadan
+6  A: 

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() {
    ...
  }
}
Edwin Buck
+1 Otherwise, B could do bad things with A not being fully constructed.
glowcoder