我是 java 的新手,我对下面的例子感到困惑
public class Test {
int testOne(){ //member method
int x=5;
class inTest // local class in member method
{
void inTestOne(int x){
System.out.print("x is "+x);
// System.out.print("this.x is "+this.x);
}
}
inTest ins=new inTest(); // create an instance of inTest local class (inner class)
ins.inTestOne(10);
return 0;
}
public static void main(String[] args) {
Test obj = new Test();
obj.testOne();
}
}
为什么我无法在第 8 行中使用“this”关键字访问 inTestOne() 方法中的阴影变量
最佳答案
why i can't access to shadowed variable in inTestOne() method with "this" keyword in line 8
因为x
不是类的成员变量;它是一个本地 变量。关键字 this
可用于访问类的成员字段,而不是局部变量。
一旦变量被隐藏,您就无法访问它。这没关系,因为变量和本地内部类都由您更改;如果你想访问被隐藏的变量,你需要做的就是重命名它(或重命名隐藏它的变量,无论你觉得更有意义)。
注意:不要忘记标记局部变量final
,否则即使它没有被隐藏,你也无法访问它。
关于java - 访问本地类中的阴影变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25490081/