Java:组件如何了解其所有者 [英] Java: how does a component know its owner
本文介绍了Java:组件如何了解其所有者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个类 A
和一个类 B
.
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!";
}
}
我知道我可以通过A获得B,因为A 拥有(或拥有拥有)B: new A().getB()
.
但是如果我有B,我能得到A吗?
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?
推荐答案
当然,只需在类B中添加例程 getA()
,然后将构造函数中的行更改为
Sure, just add routine getA()
in you class B, and change the line in your constructor to
public A() {
this.b = new B(this);
}
这当然假定您的B类具有一个接受 A
(例如
This of course assumes your class B has a constructor which accepts an A
, e.g.,
public B(A a) {
this.a = a;
}
这篇关于Java:组件如何了解其所有者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文