Define class as Observable and Observer as

technically it seems OK to define Class as Observable and Observer using the following code:

 public class Data extends Observable implements Observer 

however, trying to implement it, it does not work.

 public class Data extends Observable implements Observer { @Override public void update(Observable o, Object o1) { System.out.println("SC"); } Integer A; String B; Float C; public Data() { this.addObserver(this); } public void setA(Integer A) { this.A = A; notifyObservers(); } public void setB(String B) { this.B = B; notifyObservers(); } public void setC(Float C) { this.C = C; notifyObservers(this.C); } } 

using the main function as shown below:

 public static void main(String[] args) { Data d = new Data(); d.setA(5); d.setB("Hi"); d.setC(2.0f); } 

it should print some "SC", but it does not work. Can someone explain why?

+4
source share
1 answer

If you are not .setChanged() , then .notifyObservers() not valid. This is so if you have separate classes that define Observable and Observers, or if you have one class, as in your example.

Try changing the settings:

 public void setC(Float C) { this.C = C; setChanged(); // <-- add this line notifyObservers(this.C); } 

From the Observable documentation,

setChanged() Marks this Observable as changed ; the hasChanged method now returns true .

notifyObservers(Object arg) If this object has changed as indicated by the hasChanged method , then notify all its observers, and then call the clearChanged method to indicate that this object no longer exists.

+6
source

Source: https://habr.com/ru/post/1440275/


All Articles