Lambda Expression v/s Anonymous Inner Class – Java 8

Lambda Expression vs anynymous inner class Java8

Lambda Expression is new feature of Java 8. Before Java 8 Anonymous Inner Class was very useful to write method local implementation of any interface like ActionListner or EventListener etc. With Java 8 if an interface is a Functional Interface we can use Lambda Expression to provide implementation. Read further to know about Lambda Expression v/s Anonymous Inner Class in Java 8

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 but Lambda Expression does not. Lambda executes always within scope of surrounding context. To explain it better, in Anonymous Inner Class keyword this refers to current object of anonymous class and keyword super refers to object of super class of anonymous class. In Lambda Expression keyword this refers to object of surrounding class and keyword super 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 is compiled to invokedynamic instruction.

Please share it and help others if you found this blog helpful. Feedback, questions and comments are always welcome.

Further Reading

Comments