Java Method References
Java provides a new feature called method reference in Java 8. 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. In this tutorial, we are explaining method reference concept in detail.
Types of Method References
There are following types of method references in java:
- Reference to a static method.
- Reference to an instance method.
- Reference to a constructor.
1) Reference to a Static Method
You can refer to static method defined in the class. Following is the syntax and example which describe the process of referring static method in Java.
Syntax
Example 1
In the following example, we have defined a functional interface and referring a static method to it’s functional method say().
Output:
Hello, this is static method.
Example 2
In the following example, we are using predefined functional interface Runnable to refer static method.
Output:
Thread is running...
Example 3
You can also use predefined functional interface to refer methods. In the following example, we are using BiFunction interface and using it’s apply() method.
Output:
30
Example 4
You can also override static methods by referring methods. In the following example, we have defined and overloaded three add methods.
Output:
30 30.0 30.0
2) Reference to an Instance Method
like static methods, you can refer instance methods also. In the following example, we are describing the process of referring the instance method.
Syntax
Example 1
In the following example, we are referring non-static methods. You can refer methods by class object and anonymous object.
Output:
Hello, this is non-static method. Hello, this is non-static method.
Example 2
In the following example, we are referring instance (non-static) method. Runnable interface contains only one abstract method. So, we can use it as functional interface.
Output:
Hello, this is instance method
Example 3
In the following example, we are using BiFunction interface. It is a predefined interface and contains a functional method apply(). Here, we are referring add method to apply method.
Output:
30
3) Reference to a Constructor
You can refer a constructor by using the new keyword. Here, we are referring constructor with the help of functional interface.
Syntax
Example
Output:
Hello