Question

Suppose I have a class A and a class B.

public class A {

    private B b;

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

    public B getB() {
        return this.b;
    }
}

public class B {

    public String getSome() {
        return "Get some!";
    }
}

I know I can get B through A, because A has (or owns) B: new A().getB().
But if I have B, can I get A?

Was it helpful?

Solution

Sure, just add routine getA() in you class B, and change the line in your constructor to

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

This of course assumes your class B has a constructor which accepts an A, e.g.,

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

OTHER TIPS

B needs an explicit reference to its owner:

public class B {
  private final A owner;

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

  public A getOwner() {
    return owner;
  }
}

And in A:

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

Nope. There is no such thing as an 'owner' in Java. Any object can be referenced by any number of other objects.

If you need B to always be bound to an instance of A, make B an inner class of A:

class A {

    B b = new B();

    class B {
        String getSome() {
            // this will refer to the enclosing A
            return A.this.toString();
        }
    }
}

An inner (non-static) class always has an implicit reference to the enclosing instance and cannot exist without it. In order to instantiate B from outside, you need a nasty syntax: B b = new A().new B();

No you cannot. B has no reference to A.

No.

Class a has reference to class B, but class B has no reference to class A. References are one way only.

No, that's not possible. You're looking for backreferences, but we have to create them in the code if needed.

If you want to collect all referencers to B, you could do this with a constructor or with a factory (pattern) that creates B's. I'll show the factory:

public class B {

   private static Set<? extends Object> referencers = new HashSet<? extends Object>();
   private B(){}  // no public constructor
   public static create(Object parent) {
     // cooperative approach, the caller should pass "this"
     referencers.add(parent);
   }
   public static remove(Object parent) {
     referencers.remove(parent);
   }
}

you can also use inner classes

package test;

public class A {

B b = null;

public B getB()
{
    return b;
}

public class B {

    public A getA()
    {
        return A.this;
    }
}

public static void main(String[] args) {
    B b = new A().new B();
}

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top