简体   繁体   中英

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 this key word always refers current class inside local variable. **->**Lambda expression refers current class instance variable instead of local variable

**-> Anonymous inner class this key word always refers current class inside local variable. **-> Lambda expression refers current class instance variable instead of local variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM