In many object oriented languages such as Java, the .NET family, Python, Ruby, and I’m sure a host of others, the root object class from which all other classes inherit defines an equality checking method. However, in my experience, many of the classes I create really don’t need an equality check or I (or co-workers) don’t bother overriding the default method because we don’t intend to use it. In the latter case, the default equality method doesn’t represent equality very well for that class. So why do so many languages provide this method as part of the definition of the root object class when it seems like many classes should not? Why not leave off the equality method and force users to define it when they need it?
In many object oriented languages such as Java, the .NET family, Python, Ruby, and
Share
For any objects references
XandY, regardless of their types, it is possible to meaningfully ask and answer the question “Is the object referred to byXequivalent to the one referred to byY“. IfXrepresents a Porche 911 automobile andYrepresents a cast-iron park bench, the answer would simply be “no”. To be sure, if one knew thatXwas a car andYa bench, one likely wouldn’t bother asking, but supposeX,Y, or both, were “things that one may be asked to paint”. One might not know whether or notXandYare of the same type, and the objects are not equivalent, one may not care. Having a universal means of asking equivalence saves code the trouble of having to worry about objects’ exact type.The reason to have all objects implement
Equalsas a virtual method is that it’s the easiest mechanism by which objects can supply a definition of equivalence that is broader than referential equality. It is often useful to have immutable objects report themselves as equivalent to other objects which have the same immutable state [e.g. having two strings, both holding the six characters “GEORGE”, reported each other as equivalent] Having all objects implementEqualsas a virtual method, and having mutable objects’ implementation simply report referential equality, is generally easier than having anEqualsfunction which can only be used on immutable objects. After all, it’s not hard for an mutable object to simply report itself as unequal to anything other than itself.