Доступ к переменным в области видимости метода из анонимного класса - PullRequest
1 голос
/ 07 октября 2019

Как мне вывести 12 со значением x = 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();
    }
}

Любая помощь будет принята с благодарностью.

1 Ответ

0 голосов
/ 07 октября 2019
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();
    }
}
...