access to shadowed variable in local class

2019-02-25 14:03发布

问题:

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.