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:
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.
In the following example, we have defined a functional interface and referring a static method to it's functional method say().Test it Now
Hello, this is static method.
In the following example, we are using predefined functional interface Runnable to refer static method.Test it Now
Thread is running...
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.Test it Now
You can also override static methods by referring methods. In the following example, we have defined and overloaded three add methods.Test it Now
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.
In the following example, we are referring non-static methods. You can refer methods by class object and anonymous object.Test it Now
Hello, this is non-static method. Hello, this is non-static method.
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.Test it Now
Hello, this is instance method
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.Test it Now
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.
ExampleTest it Now