The Contract of equals
If you need logical equality (instead of object identity),
override equals()
,
and obey the contract when overriding it
(think of value classes).
Given non-null references x
, y
, and z
, the contract includes:
- Reflexive:
x.equals(x)
. - Symmetric:
x.equals(y) == y.equals(x)
. - Transitive:
x.equals(y) && y.equals(z) == x.equals(z)
. - Consistent: Multiple calls of
x.equals(y)
should yield the same result. - Non-Nullity:
x.equals(null) == false
.
And you should always also override hashCode()
when overriding equals()
.
Nevertheless, it is not always possible to obey both the contract and object-oriented principles while extending a class.
(So think twice when you want to make a “trivial” extension; use composition instead.)