This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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 ]
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
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 ]