Can you explain how the Observer pattern works in Java using Observer and Observable?

Java's original built-in Observer pattern support used the java.util.Observable class as the subject and the java.util.Observer interface for listeners, wired together so state changes automatically propagate to every registered listener.

Key Points: • A subject extends Observable and calls setChanged() followed by notifyObservers() whenever its state changes. • Observers implement the Observer interface's update(Observable o, Object arg) method to react to notifications. • Observers register interest by calling addObserver() on the Observable instance. • Observable requires setChanged() to be called before notifyObservers(), otherwise the notification is silently skipped. • Observable and Observer were deprecated in Java 9 because Observable is a class (forcing single inheritance) and lacks proper event ordering and thread-safety guarantees; modern code typically uses PropertyChangeListener, custom listener interfaces, or reactive streams instead.

Example: A WeatherStation extending Observable calls setChanged() then notifyObservers(temperature) whenever a new reading comes in, and a DisplayPanel implementing Observer receives that value through its update() method.

Code Example:

class WeatherStation extends Observable {
    void setTemperature(int temp) {
        setChanged();
        notifyObservers(temp);
    }
}

class DisplayPanel implements Observer {
    public void update(Observable o, Object arg) {
        System.out.println("New temperature: " + arg);
    }
}

Interview Tip: A concise interview answer is:

"The subject extends Observable, calls setChanged() and then notifyObservers() when its state changes, and each Observer implements update() to react. That said, Observable and Observer were deprecated in Java 9 since Observable forces single inheritance and lacks proper thread safety, so most modern code implements a custom listener interface instead."