Lambda vs Anonymous Class in Java

1. Introduction

In Java, both lambda expressions and anonymous classes are used to instantiate objects from interfaces or abstract classes without the need to create a traditional class implementation. A lambda expression is a concise way to represent an instance of a functional interface (an interface with a single abstract method), using an arrow syntax (->). An anonymous class is a more verbose way to define an instance of a class without giving it a name.

2. Key Points

1. Lambda expressions are shorter and generally more readable than anonymous classes.

2. Anonymous classes can implement interfaces with more than one method and can extend concrete classes.

3. Lambda expressions can access final or effectively final variables from their enclosing scope. Anonymous classes can access any final variables.

4. Lambda expressions cannot have a state (cannot contain instance variables), while anonymous classes can have a state.

3. Differences

Lambda Expression Anonymous Class
Can implement only interfaces with a single abstract method. Can implement interfaces with multiple methods and extend classes.
Cannot have any state (instance variables). Can maintain state in instance variables.
Has implicit implementation of the method defined by the functional interface. Requires explicit implementation of the method(s).
More limited in scope and capability compared to anonymous classes. More flexible with broader capabilities than lambda expressions.

4. Example

// Using a lambda expression
Runnable r1 = () -> System.out.println("Hello World with lambda!");

// Using an anonymous class
Runnable r2 = new Runnable() {
    @Override
    public void run() {
        System.out.println("Hello World with anonymous class!");
    }
};

public class Main {
    public static void main(String[] args) {
        r1.run();
        r2.run();
    }
}

Output:

Hello World with lambda!
Hello World with anonymous class!

Explanation:

1. The lambda expression r1 implements the Runnable interface's run method in a single line of code.

2. The anonymous class r2 also implements the Runnable interface but requires more syntax to do so.

3. Both r1 and r2 provide the same functionality, but r1 is more concise.

5. When to use?

- Use lambda expressions when working with functional interfaces for cleaner and more readable code.

- Use anonymous classes when you need to work with abstract classes or interfaces with more than one method, or when you need to maintain state within the class.

Comments