Observer and Observable Java

Observer Observable Introduction

Sometimes, it may be necessary to get notified when the data changes in a data structure. To accomplish this job, the Java designers introduced Observer and Observable classes with JDK 1.0, the starting version itself. Observer is an interface and Observable is a class, both from java.util package. As the names are indicative, Observer observes the Observable. Observer keeps on watching the Observable and when observable gets changed, informs the concerned (who have registered earlier). Similar affect is achieved with listener interfaces and adapter classes, through events, in AWT components and servlets.

Some applications of these two classes are to keep watch on purchasers of some items like explosives or contraband items etc. in a shopping mall. Another one is, if a share value gets changed, it must be informed to the share holder and also the banker where the share is pledged.

With this understanding, now let us go into the programming.

Any class that would like to watch must implement Observer interface. The Observer gets notified whenever Observable gets modified. One Observable object can be watched by many Observer objects.

Any class that would like to be observed (or watched) should extend Observable class. The notifyObservers() method of Observable class informs to all the Observer objects by calling update() method. The update() is defined in Observer interface.

In the following program, two observers exist – Principal and HOD (Head of the Department). The observable is Student. Here, Principal and HOD watch the Student. Whenever the student gets marks less than 40, the principal and HOD are informed.

Leave a Comment

Your email address will not be published.