When should I use “this” in a class?

后端 未结 18 2079
情书的邮戳
情书的邮戳 2020-11-21 23:36

I know that this refers to a current object. But I do not know when I really need to use it. For example, will be there any difference if I use x i

18条回答
  •  有刺的猬
    2020-11-22 00:14

    The second important use of this (beside hiding with a local variable as many answers already say) is when accessing an outer instance from a nested non-static class:

    public class Outer {
      protected int a;
    
      public class Inner {
        protected int a;
    
        public int foo(){
          return Outer.this.a;
        }
    
        public Outer getOuter(){
          return Outer.this;
        }
      }
    }
    

提交回复
热议问题