Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Correct equals() implementation

 
dennis zined
Ranch Hand
Posts: 330
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all.
Can the equals() method be implemented in a subclass to be symmetric (equal's contract) so that comparing a super class and sub class having the same instance attributes will result to true. Or should the overridden equals() method be implemented in the super class instead? What if I dont have access to the super class' code, is there an alternative solution which does not violate the equals() contracts?
The reason for this type of question is because I'm currently studying Chapter 7 of the K&B book and trying to understand what would work and not work for the equals implementation.
Any inputs is appreciated. Thanks.
[ December 17, 2003: Message edited by: dennis zined ]
 
Gian Franco
blacksmith
Ranch Hand
Posts: 979
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi dennis,
I�m still studying this topic myself, but I was thinking
:roll:
Suppose the equals() method is implemented in a subclass, and you have two references to two different objects: one superclass instance A and one subclass instance B.
The symmetry condition states: for any x and y, x.equals(y) should return true if and only if x.equals(y) returns true.
This means in the above mentioned case, b.equals(a) should return true if...a.equals(b), but the latter wouldn�t call the equals() method in B and it is not possible even with a downcast ((B)a).equals(b) because you would get a ClassCastException.
So I guess it�s not possible to implement it in a subclass in order to compare it with its superclass.
Maybe someone has an enlightening view.
Best regards,
Gian Franco
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Manish Hatwalne once wrote an excellent article in the Javaranch newsletter, check it out: Equals and Hash Code
 
dennis zined
Ranch Hand
Posts: 330
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Gian. Thanks for your post. I never thought I'd get a reply.
You're correct. After reading Manish Hatwalne article (Thanks Valentin for the link) I guess its not a good idea to have two objects equal to each other if one is a superclass and the other a subclass. So to be symmetric (or to follow the symmetric contract) they have to be exactly the same type. Being in the same type hierarchy is not enough.
[ December 19, 2003: Message edited by: dennis zined ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic