Java 8 Method-References

In java 8 new feature introduce method Reference.Method Reference is used to refer method of functional interface.
when we used Lambda expression to just referring a method.we can replace our lambda expression with method Reference.

Type of Method Referencess

  1. Reference to static method. (Example :ContainingClass::staticMethodName)
  2. Reference to instance method of particular object (Example :containingObject::instanceMethodName)
  3. Reference to constructor (example :ClassName:: new)


1)Reference to static method:-

  Used to refer static methods from a class

          interface TestMethod{  
              void shop();  
          }  


          public class SampleExample{  
           public static void testReferance(){  
               System.out.println("Hello,world !");  
          }  

          public static void main(String[] args) {  
          TestMethod testMethod= SampleExample::testReferance; // Referring static method  
          testMethod.shop(); // Calling interface method    
    }  


2) Reference to instance method of particular object

 In this type we are referring non-static methods. You can refer methods by class object and anonymous object.

interface TestMethod{  
    void say();  
}  

public class InstanceMethodRef {  
    public void testReferance(){  
        System.out.println("Hello, this is non-static method.");  
    }  

    public static void main(String[] args) {  
        InstanceMethodRef methodRef = new InstanceMethodRef();  
        TestMethod testMethod = methodRef::saySomething;  // Referring non-static method using reference   
            testMethod.shop();  // Calling interface method 
            // Referring non-static method using anonymous object  
            TestMethod sayable2 = new InstanceMethodRef()::testReferance;  
            // Calling interface method  
            testMethod2.shop();  
    }  
}  

3) Reference to a Constructor

 In this type , we are referring constructor with the help of functional interface.

interface TestMethod{  
    ConsMethod getMessage(String msg);  
}  
class ConsMethod{  
    Message(String msg){  
        System.out.print(msg);  
    }  
}  
public class ConstructorRef {  
    public static void main(String[] args) {  
        TestMethod hello = ConsMethod::new;  
        hello.getMessage("Hello world");  
    }  
}  

No comments: