When I read a Java book, author has said that, when designing a class, it's typically unsafe to use equals()
with inheritance. For example:
public final class Date {
public boolean equals(Object o) {
// some code here
}
}
In the class above, we should put final
, so other class cannot inherit from this. And my question is, why it is unsafe when allow another class inherit from this?
Martin Odersky (the guy behind generics in Java and the original codebase for the current
javac
) has a nice chapter in his book Programming in Scala addressing this problem. He suggests that adding acanEqual
method can fix the equality/inheritance problem. You can read the discussion in the first edition of his book, which is available online:Chapter 28 of Programming in Scala, First Edition: Object Equality
The book is of course referring to Scala, but the same ideas apply to classic Java. The sample source code shouldn't be too difficult for someone coming from a Java background to understand.
Edit:
It looks like Odersky published an article on the same concept in Java back in 2009, and it's available on the same website:
How to Write an Equality Method in Java
I really don't think trying to summarize the article in this answer would do it justice. It covers the topic of object equality in depth, from common mistakes made in equality implementations to a full discussion of Java
equals
as an equivalence relation. You should really just read it.Because it's hard (impossible?) to make it right, especially the symmetric property.
Say you have class
Vehicle
and classCar extends Vehicle
.Vehicle.equals()
yieldstrue
if the argument is also aVehicle
and has the same weight. If you want to implementCar.equals()
it should yieldtrue
only if the argument is also a car, and except weight, it should also compare make, engine, etc.Now imagine the following code:
The first comparison might yield
true
if by coincidence tank and bus have the same weight. But since tank is not a car, comparing it to a car will always yieldfalse
.You have few work-arounds:
strict: two objects are equal if and only if they have exactly the same type (and all properties are equal). This is bad, e.g. when you subclass barely to add some behaviour or decorate the original class. Some frameworks are subclassing your classes as well without you noticing (Hibernate, Spring AOP with CGLIB proxies...)
loose: two objects are equal if their types are "compatible" and they have same contents (semantically). E.g. two sets are equal if they contain the same elements, it doesn't matter that one is
HashSet
and the other isTreeSet
(thanks @veer for pointing that out).This can be misleading. Take two
LinkedHashSet
s (where insertion order matters as part of the contract). However sinceequals()
only takes rawSet
contract into account, the comparison yieldstrue
even for obviously different objects:See also