Why is it better to use the default Object equals method in Java?

equals, java, overloading, overriding

Solution

The signature of `Object.equals()` is `public boolean equals(Object)`. If you define a method `public boolean equals(MyClass)`, you're adding a new method, with a different signature, instead of overriding (or redefining, if you prefer) the `Object.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 a `Set<MyClass>`, it will consider that two instances are different, although your `equals(MyClass)` method considers them equal.

Problem

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) ```

Original source