Syntax error How can we use this and super keywords in method reference in Java?

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
Updated on: 2020-07-11T08:55:49+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements