简体   繁体   English

访问本地类中的隐藏变量

[英]access to shadowed variable in local class

i'm new in java and i confused for below example我是 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();
}
}

why i can't access to shadowed variable in inTestOne() method with "this" keyword in line 8为什么我无法在第 8 行中使用“this”关键字访问 inTestOne() 方法中的隐藏变量

why i can't access to shadowed variable in inTestOne() method with "this" keyword in line 8为什么我无法在第 8 行中使用“this”关键字访问 inTestOne() 方法中的隐藏变量

Because x is not a member variable of the class;因为x不是类的成员变量; it is a local variable.它是一个局部变量。 The keyword this can be used to access a member fields of the class, not local variables.关键字this可用于访问类的成员字段,而不是局部变量。

Once a variable is shadowed, you have no access to it.一旦变量被隐藏,您就无法访问它。 This is OK, because both the variable and the local inner class are yours to change;这是可以的,因为变量和局部内部类都由你来改变; if you want to access the shadowed variable, all you need to do is renaming it (or renaming the variable that shadows it, whatever makes more sense to you).如果你想访问被隐藏的变量,你需要做的就是重命名它(或者重命名隐藏它的变量,任何对你更有意义的东西)。

Note: don't forget to mark the local variable final , otherwise you wouldn't be able to access it even when it is not shadowed.注意:不要忘记标记局部变量final ,否则即使它没有被隐藏,您也无法访问它。

this. is used to access members - a local variable is not a member, so it cannot be accessed this way when it's shadowed.用于访问成员- 局部变量不是成员,因此当它被隐藏时不能以这种方式访问​​。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM