15.7.2 this

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 compile-time 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 (§15.11), 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.

In the example:


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;
	}

}

the class IntVector implements a method equals, which compares two vectors. 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 is also used in a special explicit constructor invocation statement, which can appear at the beginning of a constructor body (§8.6.5).