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

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 () -> “w3schools”.toString()
Reference to a constructor String::new () -> new String()

Method reference to a static method of a class

package com.w3schools;

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.w3schools;

@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.w3schools;

@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 w3schools");  
    }  
}

Output

Hello w3schools