如何在以下代码中按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();
}
}
任何帮助将不胜感激。
答案 0 :(得分:-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();
}
}