Java – access the shadowed variable in the local class

I'm new to Java, and I'm confused in the following 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 can't I use the "this" keyword in line 8 to access the shadowed variable in the intesone () method

Solution

Because x is not a member variable of this class; It is a local variable The keyword this can be used to access a member field of a class instead of a local variable

When a variable is masked, you do not have access to it It doesn't matter, because variables and local internal classes are all you want to change; If you want to access the shadow variable, all you need to do is rename it (or rename the shadow variable, whatever makes more sense to you)

Note: don't forget to mark the local variable as final, otherwise you can't access it even without shadow

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>