Advertisement
Intermediate Java, Inner Classes & Anonymous Classes

How would you implement a callback or event listener using an anonymous class, and how does this same use case increasingly get replaced by lambda expressions for functional interfaces in modern Java?

Short answer

An anonymous class implementing a functional interface (like a click listener or comparator) provides an inline, one-off implementation directly at the point of use -- for interfaces with exactly one abstract method (the definition of a functional interface), Java 8's lambda…

Save Java mock interview
Advertisement
AModel answer
An anonymous class implementing a functional interface (like a click listener or comparator) provides an inline, one-off implementation directly at the point of use -- for interfaces with exactly one abstract method (the definition of a functional interface), Java 8's lambda expressions provide a significantly more concise syntax achieving the identical result, making anonymous classes increasingly reserved specifically for cases needing more than a single method implementation, needing to access `this` referring to the anonymous class instance itself (a lambda's `this` instead refers to the ENCLOSING instance, an important semantic difference), or implementing an abstract class rather than a pure functional interface (lambdas can only implement functional interfaces, never abstract classes).
// Anonymous class: verbose, but works for any interface (functional or not)
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        System.out.println("Clicked!");
    }
});

// Lambda: concise, but ONLY works because ActionListener happens to be a functional interface
button.addActionListener(e -> System.out.println("Clicked!"));
Real-world example
A legacy Swing GUI codebase using verbose anonymous ActionListener classes throughout is gradually refactored to use concise lambda expressions wherever the listener interface has exactly one abstract method, significantly reducing boilerplate while leaving any listener interfaces with multiple methods (which lambdas can't satisfy) using the original anonymous class approach.
Likely follow-ups
  • What's the specific 'this' semantic difference between an anonymous class and a lambda that could actually change behavior if code depends on it?
  • Why can't a lambda expression implement an abstract class, even one with only a single abstract method?
Related topics