- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- How to use this and super keywords with lambda expression in Java?
- Are ‘this’ and ‘super’ keywords in Java?
- What is the difference between super and this, keywords in Java?
- Can you use both this() and super() in a constructor in Java?
- Can we use "this" keyword in a static method in java?
- Why can't we use the "super" keyword is in a static method in java?
- Super and Self Keywords in Rust Programming
- Can we cast reference variables in Java?
- Difference between super() and this() in Java
- When can we use the pack() method in Java?
- When can we use the getClass() method in Java?
- When can we use StackWalker.getCallerClass() method in Java 9?
- Can super class reference variable hold sub class's object in java?
- Can we return this keyword from a method in java?
- Difference between super() and this() in java Program

Advertisements