Course contentsShow
← Java
Lesson 646 of 2,87015. Nested and Inner ClassesFree lesson

Use Case: Event Handlers and Callbacks

Apply anonymous classes to define event listeners and callback implementations inline.

Use Case: Event Handlers and Callbacks

What you'll learn: How anonymous classes shine when defining one-off event handlers and callback implementations inline.

The Real-World Problem

When you're writing interactive programs—whether GUI applications, asynchronous tasks, or custom event systems—you often need to respond to events (button clicks, file completions, data arrivals). You could create a separate named class for each handler, but that clutters your code when the logic is simple and used only once.

Anonymous Classes to the Rescue

Anonymous classes are perfect for event handlers and callbacks because they let you define the implementation right where you need it. Think of it like giving instructions to a waiter on the spot rather than writing a formal memo.

Here's a typical pattern:

interface ClickListener {
    void onClick();
}

class Button {
    private ClickListener listener;
    
    void setClickListener(ClickListener listener) {
        this.listener = listener;
    }
    
    void click() {
        if (listener != null) {
            listener.onClick();
        }
    }
}

// Usage with anonymous class
Button saveButton = new Button();
saveButton.setClickListener(new ClickListener() {
    public void onClick() {
        System.out.println("Saving document...");
    }
});

saveButton.click(); // Prints: Saving document...

Notice how you defined the onClick behavior inline, right where you set the listener. No separate class file needed. This keeps related code together and makes the intent immediately clear.

Why This Works So Well

Anonymous classes capture the context (via the implicit outer reference and effectively final variables), letting your callback access surrounding data naturally. Perfect for quick, localized responses.

Key Takeaway:
Anonymous classes are ideal for defining event handlers and callbacks inline, keeping implementation details close to where they're registered without creating unnecessary named classes.