How do I access the method variable having the same name as the inner class member instance or method local variable of the inner class?
class A{
int a = 10; //1
public void someMethodA(){
final int a = 20; //2
class B{
int a = 30; //3
public void someMethodB(){
int a = 40; //4
System.out.println("a = "+a); //access 4
System.out.println("a = "+this.a); //access 3
System.out.println("a = "+A.this.a); //access 1
System.out.println(?????); //how do I access value of a i.e 2
}
}
}
}
I am not sure, what you actually mean, but you access a class member with the same name as a local variable with the same name like this:
Typically this pattern is used in constructors, to name the params the same as member variables, for example:
that code will never output those statements, here is an example from Sun that should explain things :
No. You can't do that. The reason being, the variable
a
in position 2 is a local variable, which can only be accessed with it's simple name, in the enclosing scope. From JLS §6.4:Now, this clears that you can only access that variable with just
a
. But, you have another variable in method local classB
which shadows that local variablea
in position 2, which is again shadowed by local variable in position 4.Now in print statement,
a
would access the variable from nearmost enclosing scope, that is local variable at position 4. If you remove that variable, it will print the variable at position 3. And then if you remove it, it will print the variable at position 2.So, the point is, there is no way to access the local variable
a
at position 2, because that is shadowed.