如何通过以下代码中的 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();
}
}
关于java - 从匿名类内部访问方法范围内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58268950/