Topics Index

Observer Demo - Java Example Program

Observer Demo
import java.util.Observable;
import java.util.Observer;

class Watcher implements Observer
    public void update(Observable obj, Object arg) // LINE A
        System.out.println("update() called, count is "
                + ((Integer) arg).intValue());

class BeingWatched extends Observable
    void counter(int period)
        for(; period >= 0; period--)
            setChanged(); // LINE B
            notifyObservers(new Integer(period)); // LINE C
            catch(InterruptedException e)
                System.out.println("Sleep interrupted");
public class MainClass
    public static void main(String args[])
        BeingWatched observed = new BeingWatched();
        Watcher observing = new Watcher();

        observed.addObserver(observing); // LINE D


update() called, count is 5
update() called, count is 4
update() called, count is 3
update() called, count is 2
update() called, count is 1
update() called, count is 0


Here in the above program Watcher become the Observer class by implementing Observer interface at LINE A we are overriding the update() in the Observer class. At LINE B we are calling setChanged() to indicate that the current object undergone change and notifying it to the Observer class by calling notifyObservers(Object arg). In the MainClass we created BeingWatched and Watcher objects and at LINE D we are adding an Observer to Observable object.

  • Check whether the current object undergone change using hasChanged()
  • Count number of Observers we have for current object using countObservers()
  • Delete all Observers for the current object using deleteObservers()

© meritcampus 2019

All Rights Reserved.

Open In App