In the following class:
public class ThreadTest {
public static String name = "Member Accessed";
public void run() {
// Anonymous class
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("Using Anonymous class, referencing this.name " + this.name);
}
};
// lambda expression
Runnable r2 = () -> {
System.out.println("Using Lambda Expression, referencing this.name " + this.name);
};
new Thread(r1).start();
new Thread(r2).start();
}
public static void main(String[] args) {
ThreadTest tt = new ThreadTest();
tt.run();
}
}
Why can the lambda expression access this.name
, whereas the anonymous class can not? I understand that for the anonymous class, this
references the anonymous class scope, and name
doesn't exist there. However, the lambda expression is basically an anonymous method that belongs to an anonymous class that implements an interface. So, technically this
should also reference the anonymous class for the lambda expression.. But somehow, this
manages to reference name
.
Why is this the case?