Method Reference in Java

Method Reference in Java is a concept introduced as part of Java 8, and its purpose is to simplify the implementation of the Functional interfaces. When you use a Lambda expression to refer to a method, you can replace your Lambda with a Method Reference. We have already covered Lambda Expressions in Java 8.

There are three types of method references:

  1. Reference to an instance method.
  2. Reference to a static method.
  3. Reference to a constructor.

1. Reference to an instance method

Syntax

java method reference

Example

Let’s first see how we can implement a Functional interface using a Lambda expression:

@FunctionalInterface
interface Drawable {
  void draw();
}

class Test {

  public void drawCircle() {
    System.out.println("Drawing circle...");
  }

  public static void main(String[] args) {
    Test test = new Test();
    Drawable drawable = () -> test.drawCircle();
    drawable.draw();
  }
}

Output: Drawing circle…

Now, let’s replace Lambda with a Method Reference:

@FunctionalInterface
interface Drawable {
  void draw();
}

class Test {

  public void drawCircle() {
    System.out.println("Drawing circle...");
  }

  public static void main(String[] args) {
    Test test = new Test();
    Drawable drawable = test::drawCircle;
    drawable.draw();
  }
}

Output: Drawing circle…

You see how the Method reference is a shortcut to writing Lambda expression.

2. Reference to a static method

Syntax

 

java method reference to a static method

Example

Let’s make a drawCircle() method static, and use the class name to refer to it:

@FunctionalInterface
interface Drawable {
  void draw();
}

class Test {

  public static void drawCircle() {
    System.out.println("Drawing circle...");
  }

  public static void main(String[] args) {
    Drawable drawable = Test::drawCircle;
    drawable.draw();
  }
}

Output: Drawing circle…

In the next lesson, we will cover the Constructor Reference in Java.

I hope this tutorial was helpful to you. To learn more, check out other Java Functional Programming tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *