Java - when “this” is the only way to go?

后端 未结 5 1115
眼角桃花
眼角桃花 2021-01-28 13:21

The following code runs for both var = putVar; & this.var = putVar;

I understand: \"this\" is used to identify that - \"put this value for just \'my\'

5条回答
  •  不要未来只要你来
    2021-01-28 13:23

    There are 2 cases I know of, aside from the case ktm mentioned (which I think is obvious and you already knew):

    1. Just to make it very clear that they're referring to the member of the current object.

      void foo(int x) {
          this.y = x; // No mistaking that y belongs to the object
      }
      
    2. If you're in an anonymous inner class within another object (ex: of class ClassName), you can use ClassName.this to get the instance of the enclosing object. The reason for this (no pun intended) is that, inside the inner class, this will refer to the inner class.

      SomeInnerClass myObj = new SomeInnerClass() {
          void bar() {
              this.y = 0; // this refers to the SomeInnerClass object
              OuterClass.this.y = 0; // OuterClass.this refers to the enclosing class OuterClass object
          }
      };
      

提交回复
热议问题