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 -
- Anonymous Inner class can implement any interface but Lambda can implement only Functional Interface, the interface with only one abstract method.
- Anonymous Inner Class can have state variables but Lambda Expression cannot. Lambda Expression is stateless.
- Lambda Expression can only access final or effectively final variables of containing method.
- 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 andsuper
keyword refers to object of super class of anonymous class. In Lambda Expressionthis
keyword refers to object of surrounding class andsuper
keyword refers to super class of surrounding class. - 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.
- 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.
- 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 - Java8Lambda Expression Basics and Syntax - Java8
kayseriescortu.com - alacam.org - xescortun.com
ReplyDeleteperde modelleri
ReplyDeletesms onay
mobil ödeme bozdurma
nft nasıl alınır
ankara evden eve nakliyat
trafik sigortası
dedektör
web sitesi kurma
AŞK KİTAPLARI
maltepe daikin klima servisi
ReplyDeletekadıköy daikin klima servisi
pendik beko klima servisi
kadıköy bosch klima servisi
maltepe arçelik klima servisi
beykoz bosch klima servisi
üsküdar bosch klima servisi
beykoz arçelik klima servisi
üsküdar arçelik klima servisi