Java: how a component knows its owner

Suppose I have class A and 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 that I can get B through A because A has (or owns) B: new A().getB() .
But if I have B, can I get A?

+1
source share
8 answers

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

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

This, of course, assumes that your class B has a constructor that takes A , for example,

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

B requires 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); } 
+2
source

Nope. In Java there is no such thing as an "owner". Any object can refer to any number of other objects.

+2
source

If you want B to always bind 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 attached instance and cannot exist without it. To create an instance of B from the outside, you need a nasty syntax: B b = new A().new B();

+1
source

No, It is Immpossible. You are looking for backlinks, but if necessary, we must create them in the code.

If you want to collect all referrers in B, you can do this with the constructor or with the factory (pattern) that creates B. I will 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); } } 
0
source

No, you canโ€™t. B has no reference to A.

0
source

No.

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

0
source

you can also use inner classes

batch test;

open 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(); } 

}

0
source

Source: https://habr.com/ru/post/1266023/


All Articles