1
votes

How can I print 12 by the value of x = 12 in the following code, Note We Can't change the variable names


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();
    }
}

Any help would be appreciated.

1
you shouldn't be able to. x=12 is a variable local to your method. In theory the master.this.x shouldn't be visible neither, but you can access it because while executing the anonymous runnable, the outer class instance exists. FYI: you should start class names with a capital letter Master, otherwise you might mistake them for a variable.GameDroids
I think only way to do that change the x=12 to xx=12 then use it directly in the runnable :) nice question thoughözkan pakdil
recommend renaming variables/fields - so it is only good for confusing readers (and bit of learning)user85421
Actually this is a nice question concerning variable name scopes and shadowing. In your case I think it's not possible to access the x of the method without renaming it.MaS
P.S., I removed the "multithreading" tag because the question appears to have nothing to do with threads.Solomon Slow

1 Answers

-1
votes
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();
    }
}