I have class named A and its component class called B.
public class A {
B myB;
...
public void bWasUpdated(){
...
List<String> list = myB.connections;
}
}
If I have an instance of B in my class A and if that instance of B gets updated somehow, how can I notify my instance of class A and call bWasUpdated()
?
I tried interfaces but ended up really confused. I guess I don't quite understand how to pass data yet between an object and its component.
EDIT
public class B {
ArrayList<String> connections;
....
public void listen(){
...
if(foundNewConnection){
this.connections.add(theNewConnection);
//Notify class A about this new connection;
}
}
}
You should use a Listener, which is a form of the pattern called the Observer pattern.
First, add this interface to your B class:
public interface ChangeListener {
public void onChangeHappened();
}
Second, add a listener variable to B with a setter:
private ChangeListener listener;
public void setChangeListener(ChangeListener listener) {
this.listener = listener;
}
Third, make A implement the ChangeListener interface and register itself as a listener:
public class A implements ChangeListener {
public A() {
myB = new B();
myB.setChangeListener(this);
}
...
public void onChangeHappened() {
// do something with B now that you know it has changed.
}
And last but not least, call your listener inside B when something changes:
public void someMethodInB() {
// change happened
if (listener != null) {
listener.onChangeHappened();
}
}
if B - inner class of A, then you can invoke in B setters (or other state-modifiers) A.this.bWasUpdated();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With