Method Local Inner Class Member scope access

后端 未结 3 748
死守一世寂寞
死守一世寂寞 2021-01-07 08:15

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{
                


        
相关标签:
3条回答
  • 2021-01-07 08:41

    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:

    A local variable (§14.4), formal parameter (§8.4.1), exception parameter (§14.20), and local class (§14.3) can only be referred to using a simple name (§6.2), not a qualified name (§6.6).

    Now, this clears that you can only access that variable with just a. But, you have another variable in method local class B which shadows that local variable a 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.

    0 讨论(0)
  • 2021-01-07 08:49

    that code will never output those statements, here is an example from Sun that should explain things :

        public class ShadowTest {
        public int x = 0;
    
        class FirstLevel {
    
            public int x = 1;
    
            void methodInFirstLevel(int x) {
                System.out.println("x = " + x);
                System.out.println("this.x = " + this.x);
                System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
            }
        }
    
        public static void main(String... args) {
            ShadowTest st = new ShadowTest();
            ShadowTest.FirstLevel fl = st.new FirstLevel();
            fl.methodInFirstLevel(23);
        }
    }
    
    0 讨论(0)
  • 2021-01-07 08:59

    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:

    public class A
    {
       int a = 10;
    
       public void someMethodA()
       {
           int a = 5;
           this.a = 20; //change the member a from 10 to 20
          a = 30; // changes the local variable, which is only known in this method to 30
       }
    }
    

    Typically this pattern is used in constructors, to name the params the same as member variables, for example:

    class Foo
    {
        private int bar = 10;
        private string fooBar = 20;
    
        public Foo(int bar, string fooBar)
        {
            this.bar = bar;
            this.fooBar = fooBar;
        }
    }
    
    0 讨论(0)
提交回复
热议问题