Java Reference
In-Depth Information
Try It Out - Observing the Observable
We'll first define a class for an object that can exhibit change:
import java.util.Observable;
public class JekyllAndHyde extends Observable {
String name = "Dr. Jekyll";
public void drinkPotion() {
name = "Mr.Hyde";
setChanged();
notifyObservers();
}
public String getName() {
return name;
}
}
Now we can define the class of person who's looking out for this kind of thing:
import java.util.Observer;
import java.util.Observable;
public class Person implements Observer {
String name; // Person's identity
String says; // What they say when startled
// Constructor
public Person(String name, String says) {
this.name = name;
this.says = says;
}
// Called when observing an object that changes
public void update(Observable thing, Object o) {
System.out.println("It's " + ((JekyllAndHyde)thing).getName() +
"\n" + name + ": " + says);
}
}
We can gather a bunch of observers to watch Dr. Jekyll with the following class:
// Try out observers
import java.util.Observer;
public class Horrific {
public static void main(String[] args) {
JekyllAndHyde man = new JekyllAndHyde(); // Create Dr. Jekyll
Observer[] crowd =
{
Search WWH ::




Custom Search