technically it seems OK to define a Class
as both Observable
and Observer
using the following code:
public class Data extends Observable implements Observer
however, trying to implement it, it's not working.
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);
}
}
with the main
function as below:
public static void main(String[] args) {
Data d = new Data();
d.setA(5);
d.setB("Hi");
d.setC(2.0f);
}
it should prints some "SC" but it's not working. Can anyone describes why?
The Java language supports the MVC architecture with two classes: Observer : Any object that wishes to be notified when the state of another object changes. Observable : Any object whose state may be of interest, and in whom another object may register an interest.
An observer is a class or structure that implements the IObserver<T> interface. The observer must implement three methods, all of which are called by the provider: IObserver<T>.
Observable is a class in the Java programming language that allows you to construct subclasses that other sections of the program can observe. Observing classes are informed when an object of this subclass changes.
If you don't .setChanged()
, then .notifyObservers()
has no effect. This is the case both if you have separate classes defining Observable and Observers, or if you have a single class, as in your example.
Try changing your setters as follows:
public void setC(Float C) {
this.C = C;
setChanged(); // <-- add this line
notifyObservers(this.C);
}
From the documentation of Observable
,
setChanged()
Marks this Observable object as having been changed; thehasChanged
method will now returntrue
.
notifyObservers(Object arg)
If this object has changed, as indicated by thehasChanged
method, then notify all of its observers and then call theclearChanged
method to indicate that this object has no longer changed.
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