How to use this and super keywords with lambda expression in Java?


The "this" and "super" references within a lambda expression are the same as in the enclosing context. Since the lambda expression doesn't define a new scope, "this" keyword within a lambda expression signifies "this" parameter of a method where the lambda expression is residing.

In the below example, this.toString() calls the toString() method of the LambdaTest object but not the toString() method of the Operate instance.

Example

@FunctionalInterface
interface Operate {
   int func(int num1, int num2);
   public String toString();
}
public class LambdaTest {
   public static void main(String[] args) {
      LambdaTest test = new LambdaTest();
      test.getResult();
   }
   public void getResult() {
      Operate op = (num1, num2) -> { // lambda expression
         System.out.println("This hashcode: " + this.hashCode());
         System.out.println("Calling toString(): "+ this.toString());
         return num1 + num2;
      };
      System.out.println("Result is: "+ funcInt.func(10, 7));
   }
   @Override
   public String toString() {
      System.out.println("Super hashcode: " + super.hashCode());
      return Integer.toString(super.hashCode());
   }
}

Output

This hashcode: 142257191
Super hashcode: 142257191
Calling toString(): 142257191
Result is: 17

Updated on: 14-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements