How to implement reference to an instance method of a particular object in Java?


Method reference is a simplified form of a lambda expression that can execute one method. It can be described using "::" symbol. A reference to the instance method of a particular object refers to a non-static method that is bound to a receiver.

Syntax

ObjectReference::instanceMethodName

Example - 1

import java.util.*;

public class InstanceMethodReferenceTest1 {
   public static void main(String[] args) {
      String[] stringArray = { "India", "Australia", "England", "Newzealand", "SouthAfrica", "Bangladesh", "WestIndies", "Zimbabwe" };
      Arrays.sort(stringArray, String::compareToIgnoreCase);
      System.out.println(Arrays.toString(stringArray));
   }
}

Output

[Australia, Bangladesh, England, India, Newzealand, SouthAfrica, WestIndies, Zimbabwe]

Example - 2

@FunctionalInterface
interface Operation {
   public int average(int a, int b);
}
class MathUtility {
   public int getAverage(int x, int y){
      return (x+y)/2;
   }
}
public class InstanceMethodReferenceTest2 {
   public static void main(String[] args) {
      MathUtility mathUtilityObject = new MathUtility();
      Operation operationObject = mathUtilityObject::getAverage;
      int result = operationObject.average(50, 30);
      System.out.println("Average of two numbers: "+ result);
   }
}

Output

Average of two numbers: 40

Updated on: 11-Jul-2020

435 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements