gpt4 book ai didi

java - 从匿名类内部访问方法范围内的变量

转载 作者:行者123 更新时间:2023-12-01 06:01:13 25 4
gpt4 key购买 nike

如何通过以下代码中的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com