• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 575
  • Last Modified:

Always favor 'instanceof' rather than getClass() in the equals( ) method


I was reading as below

Always favor 'instanceof' rather than  getClass() in the equals( ) method which takes care of super types, null comparisons.

Make sure to ensure that the equals implementation is final to preserve the symmetry contract of the method: x.equals(y) == y.equals(x).

If final seems restrictive, carefully examine to see if overriding implementations can fully maintain the contract established by the Object class.

I have not understood clearly what it means.

Please advise. Any ideas, resources, sample code highly appreciated. thanks in advance
  • 2
1 Solution
Sharon SethCommented:
It's been much debated as to what you use in the equals() method - instanceOf or getClass().
The JLS specifies that an equals() implementation should preserve symmetry  amongst other requirements .
Symmetry is where if a.equals(b) == true then b.equals(a) should also be true .
instanceOf() does not satisfy this symmetry straight away . You need to add additional checks in equals() to handle this .
So , you want to make your equals() implementation final so that anyone defining a new subclass won't  override  equals() with their own implementation and break this symmetry by ignoring the additional checks you provided.

getClass() on the other hand preserves symmetry by default , while it fails the Liskov substitutuion principle. getClass() preserves symmetry because it is not inheritance friendly , and when you use getClass() you are saying straight away that subclass instance cannot be equal to superclass instance and viceversa . This breaks Liskov substitution.
gudii9Author Commented:
where can i find more information on this subject. Seems not much written on it.
Sharon SethCommented:
Josh Bloch's Effective Java
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now