Java Observable.countObservers()
Syntax
Observable.countObservers() has the following syntax.
public int countObservers()
Example
In the following code shows how to use Observable.countObservers() method.
//from w w w . ja va2 s . c om
import java.util.Observable;
import java.util.Observer;
class ObservedObject extends Observable {
private String watchedValue;
public ObservedObject(String value) {
watchedValue = value;
}
public void setValue(String value) {
if(!watchedValue.equals(value)) {
System.out.println("Value changed to new value: "+value);
watchedValue = value;
setChanged();
notifyObservers(value);
}
}
}
class MainObserver implements Observer {
public void update(Observable obj, Object arg) {
System.out.println(obj+"called with Arguments: "+arg);
}
}
public class Main{
public static void main(String[] args) {
ObservedObject watched = new ObservedObject("Original Value");
MainObserver watcher1 = new MainObserver();
MainObserver watcher2 = new MainObserver();
watched.addObserver(watcher1);
watched.addObserver(watcher2);
int count = watched.countObservers();
System.out.println(count+" observers listening");
watched.setValue("New Value");
watched.deleteObserver(watcher1);
count = watched.countObservers();
System.out.println(count+" observers listening");
watched.setValue("Latest Value");
}
}
The code above generates the following result.
Home »
Java Tutorial »
java.util »
Java Tutorial »
java.util »