'this' in Java: How does it work?

前端 未结 7 454
孤街浪徒
孤街浪徒 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:33

    From a linguistic point of view, this is neither a local variable or a parameter. Syntactically, it is a keyword. Semantically, it is an explicit way of saying "the current object"; see JLS 15.8.3. For example:

    • this.<attributeName> explicitly refers to an instance level attribute of the current object.
    • <methodName>(this) calls a method, passing a reference to the current object as an explicit argument.

    The this keyword has other uses in Java that don't exactly mean "the current object":

    • this(<optArgumentList>) as the first statement in a constructor chains to another constructor in the same class; JLS 8.8.7.
    • <className>.this within an inner class refers to the instance of an enclosing class for the current object; JLS 15.8.4.

    From an implementation perspective, you can think of the "this" reference as a hidden or implicit parameter that gets passed each time an instance method is called. Indeed, this is more or less how the object reference is treated by the JVM's "invoke*" bytecodes. You push the target object reference onto the "opstack" followed by each of the argument values, then execute the "invoke..." instruction. (Look here for the details.).

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