When we implement an interface we inject (or accept) the contract defined by the interface.
Equalable
& Hashable
are two different contracts. But if we take a look closely then we will see that both of them depend on each other, which means they are part of a single interface
, something like EqualableAndHashable
.
Now the obvious question is, whether they should be part of this new EqualableAndHashable
interface or Object
?
Let's find out. We have ==
(equal operator) to check equality of two objects. ==
operator confirms whether values/references are equal for two different primitives/objects. But this is not always possible to answer just by checking with the ==
operator.
Now question is, whether this equality, which is also a contract, should be injected via interfaces or part of the Object class?
If we take a look, we can't just say something like:
TypeX
does not guarantee the equality contract.
It will become a chaos if some object types offer equality and some do not. Which means object of TypeX
must honor the equality contract which is true for all other object types as well. So, it must not inject equality from a interface, because equality should be the part of the contract for any object by default, otherwise it will create chaos.
So we need Objects to come up with implementation of equals
. But it can't implement only the equals
method, it also needs to implement the hashcode
method.