I have two classes as such:
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++;
}
}
The problem is that I need to have the instance of class B change the variable x in class A, the class that created class B. However, I do not know how I would let class B know that it needs to change the value or if it can. Any suggestions on how to change it would be greatly appreciated. Thank you!
You need to give your
Binstance access to theAinstance. There are a couple of ways to do that:Make
Bderive fromAand make the data fields (or accessors for them)protectedinA. I would tend to shy away from this one.Make
Baccept anAinstance in its constructor.Make
Baccept an instance of a class that implements some interface in its constructor, and haveAimplement that interface.Which you choose is up to you. I’ve given them in roughly decreasing order of coupling, where the more loosely-coupled, the better (usually).
That third option in code:
Now, both
AandBare coupled toTheInterface, but onlyAis coupled toB;Bis not coupled toA.