Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to shadowed variable in local class

Tags:

java

shadowing

I'm new to Java and I'm confused by 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 can't I access the shadowed variable in inTestOne() method with "this" keyword in line 8?

like image 346
Blaster Avatar asked May 16 '26 04:05

Blaster


2 Answers

Why can't I access the 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.

like image 156
Sergey Kalinichenko Avatar answered May 19 '26 04:05

Sergey Kalinichenko


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

like image 36
Mureinik Avatar answered May 19 '26 03:05

Mureinik