Junior — Middle
Do you think the use of anonymous classes in Java became outdated after the introduction of lambda expressions in Java 8?
sobes.tech AI
Answer from AI
Anonymous classes in Java did not become completely obsolete after the introduction of lambda expressions in Java 8, but their usage has significantly decreased. Lambdas allow writing more compact and readable code, especially for functional interfaces with a single method.
However, anonymous classes are still useful when you need to implement an interface with multiple methods or extend a class with overridden methods. Lambdas cannot replace such cases.
Example of using a lambda:
Runnable r = () -> System.out.println("Hello from lambda");
r.run();
Example of an anonymous class:
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hello from anonymous class");
}
};
r.run();
Thus, lambdas have simplified the code, but anonymous classes are still relevant in certain scenarios.