What are the method references in Java?

Java 8Object Oriented ProgrammingProgramming

Method reference is the way in a lambda expression to refer a method without executing it. In the body of a lambda expression, we can able to call another method if they are compatible with a functional interface.

The operator "::" can be used to separate the class name from the method name.

Method reference to a static method

A static method has referred by using the class name. In lambda expression, we can refer to a static method by using the below syntax.

Syntax

Class-name :: Method-name;

Example

interface Test {
   void func();
}
class StaticMethodRef {
   static void message() {
      System.out.println("Welcome to Tutorials Point");
   }
}
public class LambdaMethodRefTest1 {
   public static void main(String arg[]) {
      Test test = StaticMethodRef :: message;    // calling using "::" operator
      test.func();
   }
}

Output

Welcome to Tutorials Point


Method reference to an instance method

An instance method has referred by using a lambda expression. We need to refer an instance method, use an instance name instead of a class name. The "::" operator can be used to refer to instance methods also.

Syntax

Instance-name :: Method-name;

Example

interface Test {
   void func();
}
class InstanceMethodRef {
   void message() {
      System.out.println("Welcome to Tutorix");
   }
}
public class LambdaMethodRefTest2 {
   public static void main(String arg[]) {
      InstanceMethodRef ref = new InstanceMethodRef();
      Test test = ref :: message;   // calling using "::" operator
      test.func();
   }
}

Output

Welcome to Tutorix
raja
Published on 12-Dec-2019 15:09:20
Advertisements