我有两个这样的类(class):
public class A{
ArrayList<Runnable> classBList = new ArrayList<Runnable>();
int x = 0;
public A(){
//This code here is in a loop so it gets called a variable number of times
classBList.add(new B());
new Thread(classBList.get(classBList.size())).start();
}
}
public class B implements Runnable{
public B(){
}
public void run(){
//Does some things here. blah blah blah...
x++;
}
}
问题是我需要让 B 类的实例更改 A 类(创建 B 类的类)中的变量 x。但是,我不知道如何让 B 类知道它需要更改值或者如果可以的话。任何有关如何更改它的建议将不胜感激。谢谢!
最佳答案
您需要提供您的B
实例访问A
实例。有几种方法可以做到这一点:
制作
B
源自A
并创建数据字段(或它们的访问器)protected
在A
。我倾向于回避这个。制作
B
接受A
其构造函数中的实例。制作
B
接受在其构造函数中实现某个接口(interface)的类的实例,并具有A
实现该接口(interface)。
你的选择取决于你。我按照大致递减的耦合顺序给出了它们,其中耦合越松散越好(通常)。
代码中的第三个选项:
public TheInterface {
void changeState();
}
public class A implements TheInterface {
ArrayList<Runnable> classBList = new ArrayList<Runnable>();
int x = 0;
public A(){
//This code here is in a loop so it gets called a variable number of times
classBList.add(new B(this)); // <=== Passing in `this` so `B` instance has access to it
new Thread(classBList.get(classBList.size())).start();
}
// Implement the interface
public void changeState() {
// ...the state change here, for instance:
x++;
}
}
public class B implements Runnable{
private TheInterface thing;
public B(TheInterface theThing){
thing = theThing;
}
public void run(){
// Change the thing's state
thing.changeState();
}
}
现在,两个 A
和B
耦合到TheInterface
,但只有 A
耦合到B
; B
未耦合到A
.
关于java - 如何从我在该类中创建的类访问该类的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14932662/