我是 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() 方法中的隐藏变量?
为什么我无法使用第 8 行中的“this”关键字访问 inTestOne() 方法中的隐藏变量?
Because x
is not类的成员变量;它是一个local多变的。关键词this
可用于访问类的成员字段,而不是局部变量。
一旦变量被隐藏,您就无法访问它。这是可以的,因为变量和局部内部类都可以由你来改变;如果你想访问隐藏的变量,你需要做的就是重命名它(或者重命名隐藏它的变量,无论什么对你来说更有意义)。
注意:不要忘记标记局部变量final
,否则即使它没有被遮蔽,您也将无法访问它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)