i\'m new in java and i confused for below example
public class Test {
int testOne(){ //member method
int x=5;
class inTest // local cl
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.
this.
is used to access members - a local variable is not a member, so it cannot be accessed this way when it's shadowed.