实例 a
类A
有一个实例 b
类B
.
如何b
访问变量a
?
class A {
boolean flag;
B b;
public static void main(String[] args) {
A a = new A();
}
public A() {
b = new B();
b.doSomething();
chageFlag();
b.doSomething();
}
void changeFlag() {
// do something with flag
}
// other stuff
}
class B {
void doSomething() {
// here I need to access a from the instance owning b.
boolean aFlag = ?? // how to access a.flag ??
}
}
最佳答案
在此实例中,您将无法访问 A 的变量,因为 A 和 B 此处没有父/子或外部/内部类关系。
实现的方法是将A的实例传递给B,例如,
B b = new B(this);
为此,您需要调整构造函数以将 A 作为参数。
关于java - 如何从所有者实例访问变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59338687/