polymorphism -- overridden methods are called based on the type of the object, not the type of the reference. However, the method must also be defined for the class that the reference belongs to.
Using Point and Point3D
given:
Point pt1 = new Point(1, 2);
Point pt2 = new Point3D(1, 2, 3);
Point3D pt3d = new Point3D(1, 2, 4);
|
message |
calls |
returns |
|
pt1.equals(pt2) |
Point |
true |
|
pt2.equals(pt1) |
Point |
true |
|
pt1.equals(pt3d) |
Point |
true |
|
pt3d.equals(pt1) |
Point |
true |
|
pt2.equals(pt3d) |
Point |
true |
|
pt3d.equals(pt2) |
Point |
*true* |
|
((Point3D)pt2).equals(pt1) |
Point |
true |
|
((Point3D)pt2).equals(pt3d) |
Point3D |
false |
|
pt3d.equals((Point3D)pt2) |
Point3D |
false |
|
pt1.toString() |
Point |
"(1.0, 2.0)" |
|
pt2.toString() |
Point3D |
"(1.0, 2.0, 3.0)" |
|
pt3d.toString() |
Point3d |
"(1.0, 2.0, 4.0)" |
can we make it so that pt3d.equals(pt2) returns false? yes; replace
public boolean equals(Point3D p) { ... }
with (which now overrides the Point class equals method)
public boolean equals(Point p) {
if (p instanceof Point3D)
return (super.equals(p) && (z == ((Point3D)p).z));
else
return false;
}
|
message |
calls |
returns |
|
pt1.equals(pt2) |
Point |
true |
|
pt2.equals(pt1) |
Point3D |
false |
|
pt1.equals(pt3d) |
Point |
true |
|
pt3d.equals(pt1) |
Point3D |
false |
|
pt2.equals(pt3d) |
Point3D |
false |
|
pt3d.equals(pt2) |
Point3D |
false |