-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample3.java
More file actions
62 lines (54 loc) · 1.61 KB
/
Example3.java
File metadata and controls
62 lines (54 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package lambda_expressions;
/*
* Example demonstrating usage of this in Lambda Expressions.
* "this" keyword in lambda expression refers to enclosing class object reference.
*/
/*
* For anonymous class ‘this’ keyword resolves to anonymous class object,
* whereas for Lambda expressions ‘this’ keyword resolves to enclosing class object where lambda is written.
*/
interface Process{
public void process();
}
public class Example3 {
// enclosing class instance variable
int x = 666;
public Process getLambdaImpl() {
return () -> {
// lambda local variable
int x = 777;
System.out.println(x); // 777
System.out.println(this.x); // 666
};
}
public Process getAnonymousClassImpl(){
return new Process() {
// anonymous class instance variable
int x = 888;
@Override
public void process() {
// anonymous clas local variable
int x = 999;
System.out.println(x); // 999
System.out.println(this.x); // 888
}
};
}
public static void main(String[] args) {
Example3 example3 = new Example3();
System.out.println("Lambda Implementation");
example3.getLambdaImpl().process();
System.out.println("=======================");
System.out.println("Anonymous class Implementation");
example3.getAnonymousClassImpl().process();
}
}
/* Output:
* Lambda Implementation
* 777
* 666
* =======================
* Anonymous class Implementation
* 999
* 888
*/