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
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
gudii9Author Commented:
where can i find more information on this subject. Seems not much written on it.
Sharon SethCommented:
Josh Bloch's Effective Java
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.