Difference between Anonymous Inner class and Lambda Expressions
Key Differences Between Anonymous Inner Classes and Lambda Expressions in Java
Anonymous Inner Class:
An anonymous inner class is a class without a name and is declared and instantiated in a single statement. It can be used to create subclasses of abstract classes, interfaces, or even concrete classes on-the-fly.
Lambda Expression:
A lambda expression is a concise way to represent a functional interface (an interface with a single abstract method). It provides a clear and concise way to implement single-method interfaces using an expression or a block of code.
Anonymous Inner Class | Lambda Expressions |
It’s a class without name | It’s a method without name (anonymous function) |
Anonymous Inner Class can extend a class and implement multiple interfaces. | Lambda Expression cannot extend or implement interfaces, only provides a function implementation. (functional interface) |
Inside anonymous inner class we can Declare instance variables(objects). | Inside lambda expression we can’t Declare instance variables, whatever the variables declared are simply acts as local variables. |
Anonymous inner classes can be Instantiated. Can create Objects. | Lambda expressions can’t be instantiated. Cannot create Objects. |
Anonymous inner class is the best choice If we want to handle multiple methods. | Lambda expression is the best Choice if we want to handle interface with single abstract method (Functional Interface). |
Memory allocated on demand Whenever we are creating an object | Reside in permanent memory of JVM (Method Area). |
Inside anonymous inner class “this” Always refers current anonymous Inner class object but not outer class Object. | Inside lambda expression “this” Always refers current outer class object. That is enclosing class object. |
Examples of Anonymous Inner Class:
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Running with anonymous inner class");
}
};
new Thread(runnable).start();
Lambda Expression:
Runnable runnable = () -> System.out.println("Running with lambda expression");
new Thread(runnable).start();
Anonymous inner classes can implement multiple methods and extend classes, but they are verbose and can be harder to read. Lambda expressions, on the other hand, are concise and designed for functional interfaces, making them more readable and efficient for single-method interfaces.