this and super in Lambda Expression

this and the super keyword in Lambda are bound to the enclosing context. Lambda Expression doesn't define a new scope so this in Lambda signifies this of the class, so this in Lambda Expression will refer to the enclosing class where Lambda Expression is defined.

package org.wesome.java8;

@FunctionalInterface
interface Apple {
    String appleName = "Apple";

    public void printApple();
}

class Fuji {
    String appleName = "Fuji";
    Apple apple = () -> {
        if (this instanceof Fuji) {
            System.out.println("this apple in Functional Interface = " + this.appleName);
            System.out.println("apple in Functional Interface = " + appleName);
            System.out.println("Interface apple in Functional Interface = " + Apple.appleName);
        }
    };

    public static void main(String[] args) {
        Fuji fuji = new Fuji();
        fuji.printApple();
        fuji.apple.printApple();
    }

    public void printApple() {
        String appleName = "Gala";
        Apple apple = () -> {
            if (this instanceof Fuji) {
                System.out.println("this apple in printApple method = " + this.appleName);
                System.out.println("apple in printApple method = " + appleName);
                System.out.println("Interface apple in printApple method = " + Apple.appleName);
            }
        };
        apple.printApple();
    }
}

follow us on