Lambda Expression v/s Anonymous Inner Class - Java 8


Lambda Expression is new feature of Java 8. Before Java 8 Anonymous Inner Class was very useful to provide method local implementation of any interface like ActionListner or EventListener etc. With Java 8 if the interface is a Functional Interface we can use Lambda Expression to provide implementation.

Both of these can implement an Interface but there are subtle differences between them. Following are to the point differences between them -
  1. Anonymous Inner class can implement any interface but Lambda can implement only Functional Interface, the interface with only one abstract method.
  2. Anonymous Inner Class can have state variables but Lambda Expression cannot. Lambda Expression is stateless.
  3. Lambda Expression can only access final or effectively final variables of containing method.
  4. Scope - Anonymous Inner Class creates a new scope whereas Lambda Expression does not. Lambda executes always within scope of surrounding context. To explain it better, in Anonymous Inner Class keyword this keyword refers to current object of anonymous class and super keyword refers to object of super class of anonymous class. In Lambda Expression this keyword refers to object of surrounding class and super keyword refers to super class of surrounding class.
  5. In support to above point of Scope, Lambda Expression cannot define a variable with exactly same name as variable in containing method because of same scope.
  6. In support to above point of Scope, since Lambda expression executes within scope of surrounding class, not as if implementation of interface, lambda cannot call default method of the interface. Whereas Anonymous Inner class can call default method of the interface.
  7. Anonymous Class is actually a class without name. Which means at startup, it needs to be loaded in PermGen space and verified, object instance needs to be created to call its method. Whereas Lambda expression are compiled to invokedynamic instruction.
 
Let me know if you found this blog helpful using checkbox below. Feedback, question or comments are always welcome.

Related Articles

Functional Interface - Java8
Lambda Expression Basics and Syntax - Java8

Comments

Post a Comment

Other Popular Posts

How to enable JPA eclipselink logging in WAS Liberty

Java Thread Local Storage explained in easiest practical way

EhCache3 as JCache (JSR-107) Implementation with Cache Statistics

EhCache3 In Memory Caching for Performance Improvement