Lambda Expression is not Replacement of Anonymous Inner Class

Anonymous Inner class and lambda functions are not equal. Lambda Expression is not a replacement for Anonymous Inner Class.

package org.wesome.java8;

interface Apple {
    void show();
}

class Fuji {
    public static void main(String[] args) {
        /*-----------------------Anonymous Inner Class-----------------------*/
        Apple apple = new Apple() {
            @Override
            public void show() {
                System.out.println("i love Apple");
            }
        };
        apple.show();

        /*-----------------------Lambda Expression-----------------------*/
        Apple apple1 = () -> System.out.println("i love Apple");
        apple1.show();
    }
}
      Anonymous Inner Class       Lambda Function
1 Anonymous inner class a class is a class without a name    Lambda expression a function without a name also known as Anonymous Function
2 Anonymous inner class can implement an interface, extend the abstract and concrete class   Lambda expression can implement only functional interfaces
3 the implemented interface can have any number of methods    Only a functional interface with the Single Abstract Method (SAM) can be implemented 
4 Anonymous inner class can declare an instance variable inside    Inside lambda expression all declared variables are local.
5 Anonymous inner class can be instantiated   lambda functions cannot be instantiated
6 Best choice if needs to implement the interface with multiple methods   Lambda expression is the best choice if needs to implement Single Abstract Method (SAM)
7 The compiler will generate a separate class file for Anonymous inner class   Lambda expression is an anonymous function, hence no class file is generated
8 Memory will be allocated in Heap Memory   Lambda Functions will be stored in the method area

 

follow us on