Java Reference
In-Depth Information
} else {
return false, because o is not a Point object.
}
}
An operator called instanceof tests whether a variable refers to an object of a
given type. An instanceof test is a binary expression that takes the following form
and produces a boolean result:
<expression> instanceof <type>
Table 9.2 lists some example expressions using instanceof and their results,
given the following variables:
String s = "carrot";
Point p = new Point(8, 1);
Table 9.2 Sample instanceof Expressions
Expression
Result
s instanceof String
true
s instanceof Point
false
p instanceof String
false
p instanceof Point
true
"hello" instanceof String
true
null instanceof Point
false
The instanceof operator is unusual because it looks like the name of a method
but is used more like a relational operator such as > or == . It is separated from its
operands by spaces but doesn't require parentheses, dots, or any other notation. The
operand on the left side is generally a variable, and the operand on the right is the
name of the class against which you wish to test.
We must examine the parameter o in our equals method to see whether it is a
Point object. The following code uses the instanceof keyword to implement the
equals method correctly:
// returns whether o refers to a Point with the same (x, y)
// coordinates as this Point
public boolean equals(Object o) {
if (o instanceof Point) {
Point other = (Point) o;
return x == other.x && y == other.y;
} else { // not a Point object
 
Search WWH ::




Custom Search