SE450: Subclassing: Designing for Subclassing [2/35] Previous pageContentsNext page

java.util.Observable is designed to be subclassed.

The public interface:

public class Observable {
  public Observable();
  public void addObserver(Observer o);
  public void deleteObserver(Observer o);
  public void notifyObservers();
  public void notifyObservers(Object arg);
  public void deleteObservers();
  public boolean hasChanged();
  public int countObservers();
  ...

The protected interface:

  ...
  protected void setChanged();
  protected void clearChanged();

So to specify that the state is changed you have to be "inside" the observable...

The class is useless if you don't subclass it.

public class Counter extends Observable {
  private int _i;
  CounterObj() { _i=0; }
  public void inc() {
    _i++;
    super.setChanged();      // could replace "super" with "this" or nothing
  }
}
public class Main {
  public static void main(String[] args) {
    Counter c = new Counter();
    c.addObserver(new Observer() {
      public void update(Observable sender, Object data) {
        Counter c = (Counter) sender;
        String arg = (String) data;
        System.out.println("update(" + c + "," + arg + ")");
      }});
    c.inc();
    c.inc();
    c.notifyObservers("Dog");
  }
}

Counter.deleteObservers() is public!

At the object level:

   +-----------+
   | : Counter |
   | --------- |
   +-----------+

At the class level:

   +------------+         +------------+
   | Counter    |- - - -|>| Observable |
   +------------+         +------------+

Previous pageContentsNext page