繁体   English   中英

从匿名 class 内部访问方法 scope 中的变量

[英]Access variables in method scope from inside anonymous class

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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