Anonymous Classes and Lambdas

OOP · lesson 26 of 43 · 3 min read

What an anonymous class gives you that a lambda does not, and when each one fits.

Open this lesson in the learning hub

Key points

  • An interface with exactly one abstract method is a functional interface, so a lambda can stand in for it.
  • Default and static methods do not count towards that one, which is why Comparator is still functional.
  • A lambda is not a class: no new object identity to rely on, and this still means the enclosing object.
  • An anonymous class is a real class. Use it when you need state, several methods, or a useful toString.
  • Both capture local variables, which must be final or effectively final. The object they point at can still change.
  • Strategy in modern Java is usually a lambda parameter. Reach for a named class only when it earns a name.

Example

public class Main {
    interface Discount {                                   // one abstract method
        double apply(double amount);

        default Discount then(Discount next) {             // defaults may compose
            return amount -> next.apply(apply(amount));
        }
    }

    private final String label = "outer object";

    void demo() {
        Discount anonymous = new Discount() {              // a real class, with a real object
            @Override public double apply(double amount) { return amount - 5; }
            @Override public String toString() { return "anonymous class"; }
        };

        Discount lambda = amount -> amount * 0.9;          // no new class, no new 'this'

        System.out.println(anonymous + " -> " + anonymous.apply(100));
        System.out.println("lambda          -> " + lambda.apply(100));
        System.out.println("chained         -> " + anonymous.then(lambda).apply(100));
        System.out.println("lambda sees " + label + ", so 'this' is still Main");
    }

    public static void main(String[] args) { new Main().demo(); }
}

Lambda for one small behaviour; anonymous class when it needs state or a name.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the OOP course, and every lesson in it is listed on the OOP contents page.