Java API Tutorial - Java Observable .addObserver (Observer o)








Syntax

Observable.addObserver(Observer o) has the following syntax.

public void addObserver(Observer o)

Example

In the following code shows how to use Observable.addObserver(Observer o) method.

import java.util.Observable;
import java.util.Observer;
/*  w w  w .j  a  va2 s  .  co  m*/
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("Update called with Arguments: "+arg);
   }
}

public class Main{
   public static void main(String[] args) {
      ObservedObject watched = new ObservedObject("Original Value");
      MainObserver watcher = new MainObserver();

      watched.setValue("New Value");

      watched.addObserver(watcher);
      
      watched.setValue("Latest Value");
   }

}

The code above generates the following result.