access to shadowed variable in local class

梦想的初衷 提交于 2019-12-01 21:52:35

问题


i'm new in java and i confused for below example

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


回答1:


why i can't access to shadowed variable in inTestOne() method with "this" keyword in line 8

Because x is not a member variable of the class; it is a local variable. The keyword this can be used to access a member fields of the class, not local variables.

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.




回答2:


this. is used to access members - a local variable is not a member, so it cannot be accessed this way when it's shadowed.



来源:https://stackoverflow.com/questions/25490081/access-to-shadowed-variable-in-local-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!