Why is it considered better to use the default Object equals method in Java and modify it so it will work for a specific class (by validating with instanceof and using type casting):
public boolean equals(Object otherObject)
{
boolean isEqual = false;
if ((otherObject != null) && (otherObject instanceof myClass))
{
myClass classObject = (myClass)otherObject;
if (.....) //checking if equal
{
.....
}
instead of overloading it with a new equals method specific for each class that needs to use equals:
public boolean equals(myClass classObject)
The signature of
Object.equals()ispublic boolean equals(Object). If you define a methodpublic boolean equals(MyClass), you’re adding a new method, with a different signature, instead of overriding (or redefining, if you prefer) theObject.equals()method.Since all the collections call the
Object.equals()method, your new method would never be called by anybody except your own code, and would thus be almost useless. For example, if you create aSet<MyClass>, it will consider that two instances are different, although yourequals(MyClass)method considers them equal.