Why use lambdas over anonymous classes for functional interfaces?
Are anonymous classes really worth it?
For anyone who doesn’t know what is an anonymous class, a functional interface or lambdas, here is a small catch:-
Anonymous Class or Anonymous Inner Class is a class without a name and for which only a single object is created so that you can declare and instantiate it at the same place.
makeCall(new Callable() {
@Override
public Object call() throws Exception {
System.out.println("Hashcode:- "+this.hashCode());
return null;
}
});
A Functional interface has exactly one function to implement.
Lamda is an expression used to represent a block of code to be executed at the place of an implementaion of a functional interface.
makeCall(()->{
System.out.println("In lambda");
return null;
});
To understand the criticalness of the situation first let us look at how each of them works:-
Anonymous Class :- In simple words, its just another class with reduced capabilities.
Lamda :- If the block itself doesn’t reference any of its class fields or methods then the block is treated as a “private static” function of the class or else if it does access any of the class belongings it’s just not a “static” function anymore anymore.
Example
public class Test implements Callable {
public static void main(String args[]){
Test test=new Test();
for(int i=0;i<2;i++){
System.out.println("implementation");
makeCall(test);
}
for(int i=0;i<2;i++){
System.out.println("Anonymous");
makeCall(new Callable() {
@Override
public Object call() throws Exception {
System.out.println("Hashcode:- "+this.hashCode());
return null;
}
});
}
for(int i=0;i<2;i++){
System.out.println("Lambda");
makeCall(()->{
System.out.println("In lambda");
return null;
});
}
}
@Override
public Object call() {
System.out.println("Hashcode:- "+this.hashCode());
return null;
}
public static void makeCall(Callable callable){
try {
callable.call();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
implementation
Hashcode:- 1325547227
implementation
Hashcode:- 1325547227
Anonymous
Hashcode:- 980546781
Anonymous
Hashcode:- 2061475679
Lambda
In lambda
Lambda
In lambda
Conclusion
If you look at each approach(or the hashcodes generated above) you will clearly see that Anonymous class just instantiates a new class every time you call it. Lamda on the other hand just calls the same block of code every time you call it, hence, lesser memory leaks.