![](/img/trans.png)
[英]What would the scope change from converting a Java anonymous inner class into a Lambda expression look like?
[英]RK1. what is the behavior of "this" key word in Anonymous inner class and lambda expression
public interface Interf {
public void m1();
}
public class Test2 {
int x = 10;
public void m2() {
Interf interf = new Interf() {
int x = 20;
@Override
public void m1() {
System.out.println(this.x);
}
};
interf.m1();
}
public static void main(String[] args) {
Test2 aTest2 = new Test2();
aTest2.m2();//....................................what will get..?
}
}
public class Test3 {
int x=10;
public void m2() {
Interf interf=()->{
int x=20;
System.out.println(this.x);
};
interf.m1();
}
public static void main(String[] args) {
Test3 a=new Test3();
a.m2();
}
}
**->**Anonymous inner class 這個關鍵字總是引用局部變量中當前的class。 **->**Lambda 表達式引用當前 class 實例變量而不是局部變量
**-> Anonymous inner class 這個關鍵字總是引用局部變量中的current class。 **-> Lambda 表達式引用當前 class 實例變量而不是局部變量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.