Method Local Inner Class Member scope access

后端 未结 3 860
死守一世寂寞
死守一世寂寞 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: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;
        }
    }
    

提交回复
热议问题