Search code examples
javainheritancemethodsoverriding

What methods inherited from the Object class should usually be overridden?


I know that equals(), hashCode(), and toString() are three methods most classes should have overridden for that class and it's specific usage, but are there others I should be adding to my classes, and if so why would I use them and how do they work?


Solution

  • What methods inherited from the Object class should usually be overridden?

    None of them! Some of them can be overridden, and often are. But none of them should be overridden as a matter of course.

    The following are the methods that can be overridden:

    • toString() can be overridden if you want the result to represent aspects of the state of the target instance.

    • equals(Object) and hashCode() can be overridden1 if you want the equals semantics to be based on instance's values rather than reference identity.

    • clone() can be overridden to make clone a public method, or if the semantics of the default clone implementation are not what you need.

    • finalize() can be overridden if you want the class to be finalizable2. The remaining Object methods are final so that they cannot be overridden.


    1 - If you override one of these two methods you will most likely need to override the other to maintain the general hashCode contract. Refer to the hashCode() javadocs for details.
    2 - You probably should not do this. Finalization is deprecated and will be removed in a future Java version. There are better ways to do the cleanup that finalization was typically used for. See JEP 421 for details.