如何访问匿名类中的局部变量?

问题描述 投票:0回答:1
interface Interf {
void m1();
    }

公共类测试{

int x = 888;
Interf f;

public  void m2() {
     Integer x = 777;

    f = new Interf() {
        Integer x = 666;
        public void m1() {
            int x = 555;
            System.out.println(x);
            System.out.println(this.x);
        }
    };
}


public static void main(String[] args) {
        Test t = new Test();
        t.m2();
        t.f.m1();
}

我如何在同名的m1()方法(在匿名类中)内使用值[[777访问x变量?是否可以访问?

java anonymous-class
1个回答
0
投票
否,因为它是shadowed。但是您可以更改名称(不需要Integerint

suffice)。

public void m2() { int y = 777; f = new Interf() { int x = 666; public void m1() { int x = 555; System.out.println(x); System.out.println(this.x); System.out.println(y); } }; }
输出

555 666 777

© www.soinside.com 2019 - 2024. All rights reserved.