What is the difference between using lambda expressions and anonymous classes in Java?
sobes.tech AI
Answer from AI
Lambda expressions and anonymous classes in Java are used to create functional objects, but they have several key differences:
-
Syntax and brevity: Lambda expressions are more compact and readable, especially for simple functions. Anonymous classes require a more verbose syntax.
-
Type: Lambda expressions implement functional interfaces (interfaces with a single abstract method). Anonymous classes can implement interfaces with multiple methods or extend classes.
-
Scope: In lambdas, access to local variables is read-only (effectively final), whereas in anonymous classes, they can have their own fields and methods.
-
This context: In lambda expressions,
thisrefers to the outer class, while in anonymous classes, it refers to the anonymous class itself.
Example:
Runnable r1 = () -> System.out.println("Hello from lambda");
Runnable r2 = new Runnable() {
@Override
public void run() {
System.out.println("Hello from anonymous class");
}
};
Lambdas are preferred for simple cases, while anonymous classes are used when more complex logic or state is needed.