Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.
3 types of method references:
- Reference to a static method
- Reference to an instance method
- Reference to a constructor
Reference to a static method
Syntax
ClassName::MethodName
import java.util.function.BiFunction; class Arithmetic { public static int add(int a, int b) { return a + b; } } public class MethodReference { public static void main(String[] args) { BiFunction < Integer, Integer, Integer > adder = Arithmetic::add; int result = adder.apply(10, 20); System.out.println(result); } }
Reference to an instance method
Syntax
Object::methodName
import java.util.function.BiFunction; class Arithmetic { public int add(int a, int b) { return a + b; } } public class MethodReference { public static void main(String[] args) { Arithmetic objArithmetic = new Arithmetic(); BiFunction < Integer, Integer, Integer > adder = objArithmetic::add; int result = adder.apply(10, 20); System.out.println(result); } }
Reference to a constructor
Syntax
ClassName::new
interface Messageable { Message getMessage(String msg); } class Message { Message(String msg) { System.out.print(msg); } } public class ConstructorReference { public static void main(String[] args) { Messageable hello = Message::new; hello.getMessage("Hello"); } }