What is the meaning of “this” in Java?

后端 未结 21 2943
走了就别回头了
走了就别回头了 2020-11-21 05:41

Normally, I use this in constructors only.

I understand that it is used to identify the parameter variable (by using this.something), if i

21条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-21 05:58

    this refers to the current object.

    Each non-static method runs in the context of an object. So if you have a class like this:

    public class MyThisTest {
      private int a;
    
      public MyThisTest() {
        this(42); // calls the other constructor
      }
    
      public MyThisTest(int a) {
        this.a = a; // assigns the value of the parameter a to the field of the same name
      }
    
      public void frobnicate() {
        int a = 1;
    
        System.out.println(a); // refers to the local variable a
        System.out.println(this.a); // refers to the field a
        System.out.println(this); // refers to this entire object
      }
    
      public String toString() {
        return "MyThisTest a=" + a; // refers to the field a
      }
    }
    

    Then calling frobnicate() on new MyThisTest() will print

    1
    42
    MyThisTest a=42
    

    So effectively you use it for multiple things:

    • clarify that you are talking about a field, when there's also something else with the same name as a field
    • refer to the current object as a whole
    • invoke other constructors of the current class in your constructor

提交回复
热议问题