簡體   English   中英

RK1。 匿名內部 class 和 lambda 表達式中“this”關鍵字的行為是什么

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM