Method reference.

Before reading this I would like to suggest to go through Lamda expressions

We have seen the how to pass the behaviour as parameter.
In java8 we can pass method reference as argument.
It's not different,  same as Lambda exprssion but syntax is little change.

With lambda expression we will write like this.

interface MleInterface{
    void show();
}
 
 
public class HelloWorld{
 
  void showMsg( MleInterface mle){
      // Write some logic
      mle.show();
  }
     public static void main(String []args){
         HelloWorld  obj = new HelloWorld();
         /* Simplified Lambda expression.  */
         obj.showMsg(() -> System.out.println("I'm from Lambda expression"));
     }
}

Same we can write with method reference like below.

interface MleInterface{
    void show();
}
 
public class HelloWorld{
  void showMsg( MleInterface mle){
      // Write some logic
      System.out.println("Show method");
      mle.show();
  }
  public static void printMsg(){
      System.out.println("I'm from printMsg");
  }
  public static void main(String []args){
         HelloWorld  obj = new HelloWorld();
         /* Passing method reference.
           This way new syntax in java8.
          */
         obj.showMsg(HelloWorld :: printMsg);
     }
}


Output: Show method
I'm from printMsg

No comments:

Post a Comment