Home  >  Core Java

Java Observer and Observable Example

By Arvind Rai, September 17, 2021
On this page we will learn Java Observer and Observable example.
1. The java.util.Observer is an interface and it must be implemented by the class which needs to be informed about changes in our observable class.
2. The java.util.Observable class must be extended by the class which is being observed.
3. In Observer interface, there is a method update() that is called by Observable class.
4. The Observable class calls its setChanged() method to the change its return value as true.
5. The notifyObservers() method of Observable class notifies observers about the changes.

Now find the example. In our example news is being observed by two news readers.

Example

ObserverObservableDemo.java
package com.concretepage;
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
public 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 
Note: Since Java 9, Observer interface and Observable class have been deprecated.

References

Interface Observer
Class Observable
POSTED BY
ARVIND RAI
ARVIND RAI










©2022 concretepage.com | Privacy Policy | Contact Us