Monday 18 September 2017

Lambda Expression : Replacement of Anonymous Inner Class

Lambda Expression:
·       A new feature of java8s
·       Main intension is replacement of anonymous inner class.
·       Lambda expression is nothing but an anonymous method(method without name)

The general form is :
(para-list)->
{
   //method body

};

Let's see an example for better clarity using normal interface approach, then using anonymous inner class approach, then lambda expression approach:

Approach-1:
package java8s;

interface Transaction
{
   public void withDraw(int amt);
}

class A implements Transaction
{
   public void withDraw(int amt)
   {
       System.out.println("amount withdrawn is"+amt);
   }
}
public class LambdaExpressionExample {

   public static void main(String[] args) {
      
       A ob1=new A();  
      
       ob1.withDraw(15000);
      
   }

}

Approach-2:
package java8s;

interface Transaction
{
   public void withDraw(int amt);
}



public class LambdaExpressionExample {

   public static void main(String[] args) {
      
       Transaction ob1=new Transaction()   //Anonymous Inner Class
       {
          public void withDraw(int amt)
          {
              System.out.println("amount withdrawn is"+amt);
          }
       };
      
       ob1.withDraw(15000);
      
   }

}

Approach-3:
package java8s;

interface Transaction
{
   public void withDraw(int amt);
}
public class LambdaExpressionExample {

   public static void main(String[] args) {
       Transaction ob1=(int amt)->
          {
              System.out.println("amount withdrawn is"+amt);
          };
ob1.withDraw(1500);
       

   }

}

Output:
amount withdrawn is1500

2 comments:

  1. Thank you for sharing about lambda expression.It is very important for me.

    ReplyDelete
  2. Hii Miki, thanks for sharing your view n i will suggest you go through this blog always and gain more n more info...

    ReplyDelete