Reputation: 77
I want to override equals(Object o)
without using instanceof
, getClass()
and casting. Is this doable in Java and if yes how it is possiable?
Editing: And I want to use this method too.
For example: I want to override this method in class Cow and use it to check if my Cow logically equals to other Cow?
Thanks for answers everyone. My main problem is that: what happens if I send Car as other class to my cow or any other Object. How can I check if Object o got method getName()
(Assuming my Cow got this method)?
Upvotes: 2
Views: 508
Reputation: 120526
Sure.
Make Cow
serializable, and make sure that its serialized form is canonical (worst case by implementing Externalizable
and hand-writing your own serialization that is canonical) and then do the following in equals
:
this
.Since the serial form includes a string identifying the type, it includes the bytes necessary to distinguish instances of different types.
This isn't easy, is inefficient, is probably a maintenance nightmare, and should definitely not be your first choice, but it does demonstrate that there are language tricks available to Java code that will allow type distinction without instanceof
or Class
sameness checks.
One caveat though: the serial form does not distinguish between classes with the same name loaded in different class loaders.
Upvotes: 2
Reputation: 27549
It's certainly possible if the criteria for equality are limited to using information that is only available from an Object.
This /seems/ unlikely... why would you be overriding equals
if you were only using Object
's methods? However, there's nothing to prevent you from doing it, if this is appropriate for your design.
Just be sure that you maintain the contract defined in the Javadocs for equals()
Upvotes: 1