Method Reference in Java 8 allows a functional interface method to be mapped to a specific method using the ::
(double colon) operator. This technique simplifies the implementation of functional interfaces by directly referencing existing methods. The referenced method can be either a static method or an instance method. It’s important that the functional interface method and the specified method have matching argument types, while other elements such as return type, method name, and modifiers can differ.
If the specified method is a static method, the syntax is:
If the method is an instance method, the syntax is:
A functional interface can refer to a lambda expression and can also refer to a method reference. Therefore, a lambda expression can be replaced with a method reference, making method references an alternative syntax to lambda expressions.
Example with Lambda Expression
Example with Method Reference
In the above example, the Runnable
interface’s run()
method is referring to the Task
class’s static method printChildThread()
.
Method Reference to an Instance Method
In this example, the functional interface method process()
is referring to the Worker
class instance method display()
.
The main advantage of method references is that we can reuse existing code to implement functional interfaces, enhancing code reusability.
Constructor Reference in Java 8
We can use the ::
(double colon) operator to refer to constructors as well.
Syntax:
Example:
In this example, the functional interface Creator
is referring to the Product
class constructor.
Note: In method and constructor references, the argument types must match.
