Java 8 — Anonymous Inner Class vs Lambda Expression | Code Factory

Index Page : Link

Reference Link : Link

Donate : Link

Thread Example using Anonymous Inner Class :

Output :

Thread Example using Lambda (λ) Expression :

Output :

Anonymous Inner Class != Lambda (λ) Expression :

(1) Anonymous Inner Class that extends concrete class

(2) Anonymous Inner Class that extends abstract class

(3) Anonymous Inner Class that implements an interface which contains multiple methods

(4) Anonymous Inner Class that implements an interface which contains only one abstract method

Note : λ-Expression is only possible in last scenario. In first 3 scenario λ-Expression is not possible.

Example 1 :

Output :

Example 2 :

Output :

- Inside Anonymous inner class we can declare instance variable. Inside Lambda (λ) Expression it is not possible to declare instance variable, whatever variables declared inside Lambda (λ) Expression simply local variables only.

- Inside Anonymous inner class this always refers current inner class object. Inside Lambda (λ) Expression this always refers current outer class object only.

- Lambda (λ) Expression came to replace Anonymous inner classes is wrong statement.

- Anonymous inner class is more powerfull than Lambda (λ) Expression. A particular case of Anonymous inner class we can replace with Lambda (λ) Expression.

Example 3 :

CE : local variables referenced from a lambda expression must be final or effectively final

Advantages of Lambda (λ) Expression :

  1. We can enable functional programming in Java
  2. We can reduce length of the code so that readability wll be improved
  3. We can resolve complexity of Anonymous Inner Class until some extent
  4. We can handle procedures/functions just like values
  5. We can pass procedures/functions as arguments
  6. Easier to use updated APIs and libraries
  7. Enable support for parallel processing

Difference between Anonymous Inner Class and Lambda Expression :