Java Reference
In-Depth Information
9
super
(x, y);
10
this
.z = z;
11 }
12
13 // returns the z-coordinate of this Point3D
14
public int
getZ() {
15
return
z;
16 }
17 }
On the surface, this seems to be a reasonable implementation. However, consider
the
equals
method defined in the
Point
class. It compares the
x
- and
y
-coordinates
of two
Point
objects and returns
true
if they are the same:
// 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
return false;
}
}
You might also want to write an
equals
method for the
Point3D
class. Two
Point3D
objects are equal if they have the same
x
-,
y
-, and
z
-coordinates. The fol-
lowing is a working implementation of
equals
that is correct but stylistically
unsatisfactory:
public boolean equals(Object o) {
if (o instanceof Point3D) {
Point3D p = (Point3D) o;
return getX() == p.getX() && getY() == p.getY() && z == p.z;
} else {
return false;
}
}
The preceding code compiles and runs correctly in many cases, but it has a subtle
problem that occurs when you compare
Point
objects to
Point3D
objects. The
Point
class's
equals
method tests whether the parameter is an instance of
Point
and returns
false
if it is not. However, the
instanceof
operator will return
true
Search WWH ::
Custom Search