Interview Q&A / Object-Oriented Programming

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What is the Observer pattern? Explain with a cricket score example.

SHORT ANSWER

A subject keeps a list of observers and tells all of them when its state changes. Observers subscribe and unsubscribe at runtime, and the subject does not need to know what they do with the news.

Explain it simply

A live cricket score. The scoreboard is the subject. The mobile app, the TV graphic and the radio commentator all subscribe. When a wicket falls, the scoreboard announces it once and everybody who subscribed gets the update. The scoreboard does not know or care how each one uses it.

Example

java
interface ScoreListener { void onScore(int runs, int wickets); }

class Match {
    private final List<ScoreListener> listeners = new ArrayList<>();
    private int runs, wickets;

    void subscribe(ScoreListener l)   { listeners.add(l); }
    void unsubscribe(ScoreListener l) { listeners.remove(l); }

    void wicket(int runsOnBall) {
        runs += runsOnBall;
        wickets++;
        for (ScoreListener l : listeners) l.onScore(runs, wickets);
    }
}

Match m = new Match();
m.subscribe((r, w) -> System.out.println("App: " + r + "/" + w));
m.subscribe((r, w) -> System.out.println("TV: " + r + "/" + w));
m.wicket(0);
// App: 0/1
// TV: 0/1

The Match class depends only on the ScoreListener interface, so new kinds of listeners need no change to it.

What to say in the interview

"Observer defines a one-to-many dependency: when the subject changes, all subscribed observers are notified automatically. It decouples the subject from the observers, which is the basis of event listeners, UI updates and notification systems."

Common mistakes

  • Forgetting to unsubscribe, which keeps old observers alive and receiving events.

#design-patterns#observer#java

Related questions

Practise more Object-Oriented Programming questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Object-Oriented Programming quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.