Java Method ReferencesJava 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 ReferencesThere are following types of method references in java:
1) Reference to a Static MethodYou 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 1In the following example, we have defined a functional interface and referring a static method to it's functional method say(). Test it NowOutput: Hello, this is static method. Example 2In the following example, we are using predefined functional interface Runnable to refer static method. Test it NowOutput: Thread is running... Example 3You 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 NowOutput: 30 Example 4You can also override static methods by referring methods. In the following example, we have defined and overloaded three add methods. Test it NowOutput: 30 30.0 30.0 2) Reference to an Instance Methodlike static methods, you can refer instance methods also. In the following example, we are describing the process of referring the instance method. Syntax Example 1In the following example, we are referring non-static methods. You can refer methods by class object and anonymous object. Test it NowOutput: Hello, this is non-static method. Hello, this is non-static method. Example 2In 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 NowOutput: Hello, this is instance method Example 3In 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 NowOutput: 30 3) Reference to a ConstructorYou can refer a constructor by using the new keyword. Here, we are referring constructor with the help of functional interface. Syntax ExampleTest it NowOutput: Hello Next TopicJava 8 Functional Interfaces |