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 can we use this and super keywords in method reference in Java?
The method reference is similar to a lambda expression that refers to a method without executing it and "::" operator can be used to separate a method name from the name of an object or class in a method reference.
The methods can be referenced with the help of this and super keywords in Java. The super keyword can be used as a qualifier to invoke the overridden method in a class or an interface.
syntax
this::instanceMethod TypeName.super::instanceMethod
Example
import java.util.function.Function;
interface Defaults {
default int doMath(int a) {
return 2 * a;
}
}
public class Calculator implements Defaults {
@Override
public int doMath(int a) {
return a * a;
}
public void test(int value) {
Function<Integer, Integer> operator1 = this::doMath;
System.out.println("this::doMath() = " + operator1.apply(value));
Function<Integer, Integer> operator2 = Defaults.super::doMath;
System.out.println("Defaults.super::doMath() = " + operator2.apply(value));
}
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.test(10);
}
}
Output
this::doMath() = 100 Defaults.super::doMath() = 20
Advertisements