java - 从匿名类内部访问方法范围内的变量

标签 java variables scope shadowing

如何通过以下代码中的 x = 12 值打印 12, 注意我们无法更改变量名称


public class Master {
    final static int x = 10;

    private void display() {
        final int x = 12; // How to print this in run() method

        Runnable r = new Runnable() {
            final int x = 15;

            @Override
            public void run() {
                final int x = 20;

                System.out.println(x);  //20
                System.out.println(this.x); //15
                System.out.println();// What to write here to print (x = 12)
                System.out.println(Master.x); //10
            }
        };

        r.run();
    }

    public static void main(String[] args) {
        Master m = new Master();
        m.display();
    }
}

如有任何帮助,我们将不胜感激。

最佳答案

public class Master {
    final int x = 10;

    private void display() {
        final int x = 12;

        class RunImpl implements Runnable {
            int xFromAbove;
            int x = 15;

            private RunImpl(int x) {
                this.xFromAbove = x;
            }

            @Override
            public void run() {
                final int x = 20;
                System.out.println(x);               //20
                System.out.println(this.x);          //15
                System.out.println(this.xFromAbove); //12
                System.out.println(Master.this.x);   //10
            }
        }

        RunImpl r = new RunImpl(x);
        r.run();
    }

    public static void main(String[] args) {
        Master m = new Master();
        m.display();
    }
}

关于java - 从匿名类内部访问方法范围内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58268950/

相关文章:

java - 无法单击 Selenium 中网格上的过滤器

java - 如何在java中获取所有索引的字段映射

java - 两个时区之间的总飞行时间?

xml - Liquibase 替换 <property> 标签值?

c# - 值设置正确但在使用时为空

python - 如果 Python 一次执行一行,为什么它可以在变量声明之前看到它们?

multithreading - 在 Rust 中并行处理树

java - ColorFilter 仅特定颜色

C++编程效率

JavaScript - 单击图像,然后单击 div,然后将图像移动到 div