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
Type
Syntax
Example
Reference to a static method
Class::staticMethodName
String::valueOf
Reference to an instance method
object::instanceMethodName
x::toString
Reference to a constructor
ClassName::new
String::new
Lambda expression and Method references:
Type
As Method Reference
As Lambda
Reference to a static method
String::valueOf
(s) -> String.valueOf(s)
Reference to an instance method
x::toString
() -> “w3spoint”.toString()
Reference to a constructor
String::new
() -> new String()
Method reference to a static method of a class
packagecom.w3spoint;publicclass MethodReference {publicstaticvoid ThreadStatus(){System.out.println("Thread is running...");}publicstaticvoid main(String[] args){Thread t2=newThread(MethodReference::ThreadStatus);
t2.start();}}
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...
Thread is running...
Method reference to an instance method of an object
packagecom.w3spoint;
@FunctionalInterface
interface DisplayInterface{void display();}publicclass MethodReference {publicvoid sayHello(){System.out.println("Hello Jai");}publicstaticvoid 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();}}
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();
}
}