2

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?

xenonite
  • 1,671
  • 4
  • 28
  • 43
  • 2
    how does it complain? My eclipse doesn't – Bozho Jul 01 '10 at 16:00
  • 1
    0 My javac (Sun 1.6) accepts this code, both in Java 5 and in Java 6 mode. Is Eclipse giving you a warning (yellow) or an error (red)? What is the precise message? – Thomas Jul 01 '10 at 16:02

4 Answers4

10

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
  • 69,361
  • 7
  • 100
  • 138
5

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
  • 191,408
  • 23
  • 240
  • 301
2

Look, here is a way to use a constructed self instance in the constructer itself:

public class Foo {
    private int x;

    public Foo() {
        this(1);
        // the self instance should have been constructed now
    }

     public Foo(int x) {
        this.x = x;
     }
}

How do I call one constructor from another in Java?

Community
  • 1
  • 1
voddan
  • 31,956
  • 8
  • 77
  • 87
0

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
  • 73,784
  • 33
  • 194
  • 347