首页 > 解决方案 > 如何访问匿名类中的局部变量?

问题描述

interface Interf {
    void m1();
}

public class Test {

    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

解决方案


不,因为它被遮蔽了。但是您可以更改名称(不需要Integer,int足够了)。

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

推荐阅读