'this' in Java: How does it work?

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

    Instance methods are invoked within the context of an actual instance, an actual object.

    Within the instance method of a class, this (in most context) refers to this object. This is a relative reference: when the same method is invoked on another object, then this within the execution of that method now refers to this second object.

    For completeness, it should be mentioned that Java also has what is called "qualified" this that can be used to refer to not the object that the method is invoked upon, but the enclosing object of an inner class.

    It can also appear, with some restriction, in constructors, to invoke another constructor of the same class. super can also be used in this manner.

    References

    • JLS 15.8.3 this
      • When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method was invoked, or to the object being constructed.
    • JLS 15.8.4 Qualified this
      • Any lexically enclosing instance can be referred to by explicitly qualifying the keyword this.
    • JLS 8.8.7.1 Explicit Constructor Invocations
      • Alternate constructor invocations begin with the keyword this (possibly prefaced with explicit type arguments). They are used to invoke an alternate constructor of the same class.

提交回复
热议问题