The use of “this” in Java

后端 未结 13 1851
-上瘾入骨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:37

    You might want to take a look at What is the advantage of having this/self pointer mandatory explicit?
    Although using this is not mandatory in Java as you noticed I'm sure it will shed some light on the subject of using this in Java as well.

    0 讨论(0)
  • 2020-12-09 22:41

    To avoid this, use an IDE (like Eclipse) and it will generate warnings in this case.

    Also, make your fields final unless they absolutely can't be. There are a number of reasons (apart from this one) to do that.

    0 讨论(0)
  • 2020-12-09 22:44

    In your constructor code, you are assigning variables to themselves. 'j' is the j specified in the argument for the constructor. Even if it was the class variable j defined above, then you are still saying "j = j" ... i.e. j isn't going to evaluate differently on the left and on the right.

      public Example(int j, int k) {
           this.j = j;
           this.k = k;
      }
    
    0 讨论(0)
  • This doesn't quite answer your question, but if you use Eclipse you might find "Assignment has no effect" setting useful. I am sure this will be in other IDEs too.

    0 讨论(0)
  • 2020-12-09 22:45

    Just like Robert Grant said, 'this' is how you make it clear that you are referring to a member variable instead of a local variable.

    0 讨论(0)
  • 2020-12-09 22:48

    this is useful when you want to return the object itself

    return this;
    

    This is useful because if a class has for example Method1() and Method2(), both returning this, you are allowed to write calls like

    object.Method1().Method2()
    

    Also inside a method it can be useful to pass the object itself to another function, during a call.

    0 讨论(0)
提交回复
热议问题