When should I use “this” in a class?

后端 未结 18 2191
情书的邮戳
情书的邮戳 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:01

    this does not affect resulting code - it is compilation time operator and the code generated with or without it will be the same. When you have to use it, depends on context. For example you have to use it, as you said, when you have local variable that shadows class variable and you want refer to class variable and not local one.

    edit: by "resulting code will be the same" I mean of course, when some variable in local scope doesn't hide the one belonging to class. Thus

    class POJO {
       protected int i;
    
       public void modify() {
          i = 9;
       }
    
       public void thisModify() {
          this.i = 9;
       }
    }
    

    resulting code of both methods will be the same. The difference will be if some method declares local variable with the same name

      public void m() {
          int i;
          i = 9;  // i refers to variable in method's scope
          this.i = 9; // i refers to class variable
      }
    

提交回复
热议问题