访问本地类中的shadowed变量

我是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()方法中的shadowed变量

为什么我无法使用第8行中的“this”关键字访问inTestOne()方法中的shadowed变量

因为x 不是类的成员变量; 它是一个局部变量。 关键字this可用于访问类的成员字段,而不是本地变量。

变量被遮蔽后,您无权访问它。 这没关系,因为变量和本地内部类都是你自己要改变的; 如果你想访问阴影变量,你需要做的就是重命名它(或重命名阴影它的变量,无论什么对你更有意义)。

注意:不要忘记将局部变量标记为final ,否则即使没有阴影,也无法访问它。

this. 用于访问成员 – 局部变量不是成员,因此当它被遮蔽时不能以这种方式访问​​。