access to shadowed variable in local class

前端 未结 2 797
野趣味
野趣味 2021-01-20 15:15

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         


        
相关标签:
2条回答
  • 2021-01-20 15:17

    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.

    0 讨论(0)
  • 2021-01-20 15:21

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

    0 讨论(0)
提交回复
热议问题