The use of “this” in Java

后端 未结 13 1948
-上瘾入骨i
-上瘾入骨i 2020-12-09 21:58

If I write the following class:

public class Example {

      int j;
      int k;

      public Example(int j, int k) {
           j = j;
           k = k;
          


        
13条回答
  •  暖寄归人
    2020-12-09 22:55

    If you say just j in your constructor then the compiler will think you mean the argument in both cases. So

    j = j;
    

    simply assigns the value of the argument j to the argument j (which is a pretty pointless, but nonetheless valid statement).

    So to disambiguate this you can prefix this. to make clear that you mean the member variable with the same name.

    The other use of this is when you need to pass a reference to the current object to some method, such as this:

    someObject.addEventListener(this);
    

    In this example you need to refer to the current object as a whole (instead of just a member of the object).

提交回复
热议问题