Java method reference to an instance method of an object example

This source code example demonstrates the usage of the Java method reference to an instance method of an object.

Well, a Java method reference to an instance method of an object is a type of method reference introduced in Java 8.

Method reference is used to refer method of the functional interface. It is a compact and easy form of a lambda expression. 

If you have a lambda expression that refers to the instance method of an object then you can replace it with a method reference.

Syntax :

containingObject::instanceMethodName 

Java method reference to an instance method of an object example

In this below example, we are using method reference to call MethodReferencesDemo class object method:

package com.java.lambda.methodref;

@FunctionalInterface
interface Printable{
    void print(String msg);
}

public class MethodReferencesDemo {

    public void display(String msg){
        msg = msg.toUpperCase();
        System.out.println(msg);
    }

    public static int addition(int a, int b){
        return ( a + b);
    }

    public static void main(String[] args) {
        // 2. Method reference to an instance method of an object
        MethodReferencesDemo methodReferencesDemo = new MethodReferencesDemo();

        // lambda expression
        Printable printable = (msg) -> methodReferencesDemo.display(msg);
        printable.print("hello world!");

        // using method reference
        Printable printableMethodRef = methodReferencesDemo::display;
        printableMethodRef.print(" hello world!");
    }
}

Output:

HELLO WORLD!
 HELLO WORLD!

Related Source Code Examples


Comments