Constructor invocation syntax
>>-this-(-+--------------+-)-;->< '-ArgumentList-'
Expression syntax
>>-this-+---------------+->< '-.-ClassMember-'
Description
The keyword this may be used only in the body of an instance method or
constructor, or in the initializer of an instance variable of a class. If it appears
anywhere else, a compilation error occurs. 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. The type of this is the class C
within which the keyword this occurs. At run time, the class of the actual
object referred to may be the class C or any subclass of C.
Example
In the following example the class IntVector implements a method equals, which compares
two vectors:
class IntVector { int[] v; boolean equals(IntVector other) { if (this == other) return true; if (v.length != other.v.length) return false; for (int i = 0; i < v.length; i++) if (v[i] != other.v[i]) return false; return true; } }
If the other vector is the same vector object as the one for which the equals method was invoked, then the check can skip the length and value comparisons. The equals method implements this check by comparing the reference to the other object to this.
The keyword this can also be used to access a hidden field x, using the form this.x. This form typically appears in constructors:
class Pair { Object first, second; public Pair(Object first, Object second) { this.first = first; this.second = second; } }
Syntax diagrams
Class constructors
Source: The Java Language Specification. Copyright (C) 1996 Sun Microsystems, Inc.