Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements