What is the difference between a Lambda Expression and an Anonymous Inner Class?

Lambda expressions and anonymous inner classes both let you supply behavior without a named top-level class, but a lambda is a compact syntax limited to implementing a single functional interface method, while an anonymous class can implement multiple methods and has its own distinct scope and type identity.

Key Points: • A lambda can only target a functional interface (one abstract method); an anonymous class can implement any interface or extend any class, with any number of methods. • Inside a lambda, this refers to the enclosing instance; inside an anonymous class, this refers to the anonymous class instance itself. • Anonymous classes create a genuinely new class file at compile time (Outer$1.class); lambdas are compiled using invokedynamic and don't necessarily generate a separate class per call site. • Anonymous classes can declare their own instance fields and additional helper methods; lambdas cannot — they're limited to the single expression or block implementing the interface method. • Lambdas are generally more lightweight and readable for simple, single-method use cases like Comparators or event handlers.

Example: Implementing a Runnable with new Runnable() { public void run() {...} } is an anonymous class, whereas Runnable r = () -> {...} achieves the same result as a lambda with far less boilerplate — but only because Runnable happens to be a functional interface.

Code Example:

// Anonymous inner class
Runnable r1 = new Runnable() {
    @Override
    public void run() {
        System.out.println("Anonymous class: " + this);
    }
};

// Lambda expression
Runnable r2 = () -> System.out.println("Lambda: " + this);

Interview Tip: A concise interview answer is:

"Both let you supply behavior inline, but a lambda only works for a functional interface with a single abstract method, while an anonymous class can implement multiple methods or extend a class. The key gotcha is this: inside a lambda it refers to the enclosing instance, but inside an anonymous class it refers to the anonymous class instance itself — that trips people up in interviews."