Observer and Observable Java

Observer and Observable Java

Example on the usage of classes Observer Observable

Observer Observable
Output screenshot on Observer Observable

The classes Principal and HOD implements Observer interface as they are interested to observe. The class Student extends Observable as student should get observed.

public void update(Observable oble, Object obj1)
{
System.out.println("HOD is observing " + obj1);
}

update() is the only abstract method of Observer interface which must be overridden. This method is implicitly called when the Observable object gets changed. The Observable object, oble, is passed as first parameter. The code calls notifyObservers() method of Observable class to notify all the observers earlier registered. The second parameter, obj1, is passed by notifyObservers() method.

public void warn(Integer marks)
{
setChanged();
if(marks.intValue() < 40) { notifyObservers(marks); } }

warn() is an user-defined method which calls notifyObservers() method when the marks are less than 40. setChanged() method notifies the Observable object when a change happens. notifyObservers() method requires an object as parameter and for this reason Integer object is passed as parameter (and not int).

s1.addObserver(p1);
s1.addObserver(h1);

addObserver() is the method of Observable class with which an Observable object links with Observer interface. Here, the Student object, s1, is linked (registered) with two observers, p1 of Principal and h1 of HOD. This is the place where actual link between Observer and Observable comes in. The countObservers() method returns the number of Observer objects registered with the Observable object.

s1.deleteObserver(p1);

The Observable object can unregister or delink with the Observer with deleteObserver() method. As the Principal object is delinked, when the Student object, s1 gets 20 marks, he is not notified but HOD is notified. See the screenshot.

Leave a Reply

Your email address will not be published. Required fields are marked *