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.
x=12
is a variable local to your method. In theory themaster.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 letterMaster
, otherwise you might mistake them for a variable. – GameDroids