Home  >  Core Java

Example of Observer and Observable in Java

By Arvind Rai, June 09, 2013
java.util.Observer is an interface and it must be implemented by the class which should be informed by changes in observable class. Observable class should be extended by the class which is being observed. In Observer interface, there is a method update() that is called by Observable. Observable class calls setChanged() method to the change true. notifyObservers() method notifies observer about the change. In the below example News is being observed by two news reader.

ObserverObservableDemo.java
package com.concretepage.util;
import java.util.Observable;
import java.util.Observer;

// First observer 
class FirstNewsReader implements Observer {
    public void update(Observable obj, Object arg) {
        System.out.println("FirstNewsReader got The news:"+(String)arg);
    }
}

//Second Observer
class SecondNewsReader implements Observer {
    public void update(Observable obj, Object arg) {
        System.out.println("SecondNewsReader got The news:"+(String)arg);
    }
}

// This is the class being observed.
class News extends Observable {
    void news() {
        String[] news = {"News 1", "News 2", "News 3"};
        for(String s: news){
            //set change
            setChanged();
            //notify observers for change
            notifyObservers(s);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("Error Occurred.");
            }
        }
    }
}

//Run Observer and Observable
class ObserverObservableDemo {
    public static void main(String args[]) {
        News observedNews = new News();
        FirstNewsReader reader1 = new FirstNewsReader();
        SecondNewsReader reader2 = new SecondNewsReader();
        observedNews.addObserver(reader1);
        observedNews.addObserver(reader2);
        observedNews.news();
        
    }
}


Output
SecondNewsReader got The news:News 1
FirstNewsReader got The news:News 1
SecondNewsReader got The news:News 2
FirstNewsReader got The news:News 2
SecondNewsReader got The news:News 3
FirstNewsReader got The news:News 3
 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us