Java Reference
In-Depth Information
A class literal evaluates to the Class object for the named type (or for void ) as defined by the
defining class loader (§ 12.2 ) of the class of the current instance.
15.8.3. this
The keyword this may be used only in the body of an instance method, instance initializer,
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.12 ), or to the object being con-
structed.
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 .
The keyword this is also used in a special explicit constructor invocation statement, which
can appear at the beginning of a constructor body (§ 8.8.7 ) .
Example 15.8.3-1. The this Expression
Click here to view code image
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;
}
}
Here, 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 .
Search WWH ::




Custom Search