'this' in Java: How does it work?

前端 未结 7 463
孤街浪徒
孤街浪徒 2020-12-11 16:50

I know that \'this\' is acting as reference in Java. We can use it inside the class members only.

What I am asking is... because it is used in the members of the cl

7条回答
  •  青春惊慌失措
    2020-12-11 17:14

    "this" is implicitly passed as argument for every non-static method call you make. You can think of it as syntactical sugar, but at machine level, it is indeed an additional parameter which gets passed.

    class Person
    {
      string name;
      int age;
      void print(){ System.out.writeln(name+" "+age); }
    }
    

    works like that (pseudo-code):

    class Person
    {
      string name;
      int age;
    }
    
    void print(Person this)
    {
      System.out.writeln(this.name+" "+this.age);
    }
    

提交回复
热议问题