Re: Casting an object in equals Java 5
Andreas Leitgeb wrote:
Eric Sosman <Eric.Sosman@sun.com> wrote:
Andreas Leitgeb wrote:
PS: I think, that "normal" programs should never have a need
for .getClass(). (Application servers are not "normal" and
neither are class viewers in this context :-)
One of the few places where .getClass() seems essential is in
implementing .equals() for non-final classes:
In my Java classes they told me not to do that at all.
Either make these classes (or equals() itself, along with
hashCode()) final or abstract.
Maybe I've misunderstood, but this seems crazy. Did they
really tell you that non-final classes should not implement
equals()? That would seem to imply that they also should
not implement hashCode(), and thus be only marginally usable
in HashMaps and the like. No, I *must* have misunderstood you.
Btw., I think that class-equality is not a necessary
condition for a contract-fulfilling (and non-trivial)
equals(). It's quite feasible, that a subclass, while
adding new fields and stuff, still adheres to the base-
class' definition of equality. Proper implementation
of this behaviour would have final equals() & hashCode()
in the non-final baseclass.
Yes, I've done that. But only once: it's pretty rare
that two objects with different behaviors (because of their
different classes) should consider themselves equal to
each other.
class Super {
public boolean equals(Object obj) {
if (obj.getClass() != Super.class) return false;
If it were really necessary, I'd probably rather do it
as: if (obj.getClass() != getClass()) return false;
to also deal with classes that do not override equals()
but still want their instances to be able to equal other
instances of the same subclass, or even themselves, based
only on baseclass features.
An excellent point. Thanks!
--
Eric Sosman
esosman@ieee-dot-org.invalid