Java 8 Method References

Java 8 introduced a new feature “Method Reference” which is used to refer the methods of functional interfaces. It is a shorthand notation of a lambda expression to call a method. We can replace lambda expression with method reference (:: operator) to separate the class or object from the method name.

Types of method references

TypeSyntaxExample
Reference to a static methodClass::staticMethodNameString::valueOf
Reference to an instance methodobject::instanceMethodNamex::toString
Reference to a constructorClassName::newString::new

 

Lambda expression and Method references:

TypeAs Method ReferenceAs Lambda
Reference to a static methodString::valueOf(s) -> String.valueOf(s)
Reference to an instance methodx::toString() -> “w3spoint”.toString()
Reference to a constructorString::new() -> new String()

Method reference to a static method of a class

package com.w3spoint;
 
public class MethodReference {
	    public static void ThreadStatus(){  
	        System.out.println("Thread is running...");  
	    }  
	    public static void main(String[] args) {  
	        Thread t2=new Thread(MethodReference::ThreadStatus);  
	        t2.start();       
	    }  
}

Output

Thread is running...

Method reference to an instance method of an object

package com.w3spoint;
 
@FunctionalInterface  
interface DisplayInterface{  
    void display();  
}  
 
public class MethodReference {
	public void sayHello(){  
		System.out.println("Hello Jai");  
	}  
	public static void main(String args[]){
		MethodReference methodReference = new MethodReference();
		// Method reference using the object of the class
		DisplayInterface displayInterface = methodReference::sayHello;
		// Calling the method of functional interface
		displayInterface.display();
	}
}

Output

Hello Jai

Method reference to a constructor

package com.w3spoint;
 
@FunctionalInterface 
interface DisplayInterface{  
    Hello display(String say);  
}  
class Hello{  
    public Hello(String say){  
        System.out.print(say);  
    }  
}  
public class MethodReference {  
    public static void main(String[] args) { 
    	//Method reference to a constructor
    	DisplayInterface ref = Hello::new;  
        ref.display("Hello w3spoint");  
    }  
}

Output

Hello w3spoint
Content Protection by DMCA.com
Please Share