Lion
Lion

Reputation: 77

Is is possible to override equals without using instanceof and getClass?

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

Answers (2)

Mike Samuel
Mike Samuel

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:

  1. Try to serialize the argument. If that fails, return false.
  2. Serialize this.
  3. Compare the serialized bytes of the two.

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

Dancrumb
Dancrumb

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

Related Questions