【问题标题】:Access variables in method scope from inside anonymous class从匿名类内部访问方法范围内的变量
【发布时间】:2019-10-07 11:47:12
【问题描述】:

如何在下面的代码中通过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();
    }
}

任何帮助将不胜感激。

【问题讨论】:

  • 你不应该这样做。 x=12 是您方法的本地变量。从理论上讲,master.this.x 也不应该是可见的,但是您可以访问它,因为在执行匿名可运行文件时,外部类实例存在。仅供参考:您应该以大写字母Master 开头类名,否则您可能会将它们误认为是变量。
  • 我认为唯一的方法是将 x=12 更改为 xx=12 然后直接在可运行对象中使用它:) 很好的问题
  • 建议重命名变量/字段 - 所以它只对混淆读者有好处(和一点学习)
  • 实际上这是一个关于变量名范围和阴影的好问题。在您的情况下,我认为不重命名就无法访问该方法的 x。
  • PS,我删除了“多线程”标签,因为这个问题似乎与线程无关。

标签: java variables scope shadowing


【解决方案1】:
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();
    }
}

【讨论】:

  • 在这种情况下,您在构造函数中覆盖 x = 15。
  • 不错的解决方法,尽管this.x (15) 将不再可用
  • 重命名变量会好很多
  • 如果要更改代码,请将 x = 12 更改为 y = 12。然后只需打印 y。
  • 抱歉,您不能更改变量名
猜你喜欢
  • 2013-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-16
  • 1970-01-01
相关资源
最近更新 更多