Video in progress

Which methods of the java.lang.Object class do you override most often, and why?

Most often equals(), hashCode() and toString(). The first two are so objects can be compared by content and work correctly in hash collections, and toString() is for a readable form in logs and debugging.

📖 Answer

The methods of Object are: equals, hashCode, toString, getClass, clone, notify, notifyAll, wait. (finalize has been deprecated since Java 9 and is not used.)

The default behavior is often not enough:

User u = new User(1L, "ali@mail.uz");
log.info("Foydalanuvchi: {}", u);   // User@1b6d3586: useless

The rules:

  • If you override equals, you must override hashCode too. Equal objects must have the same hash, otherwise HashMap/HashSet can't find them.
  • Don't put sensitive data like a password or card number into toString; it ends up in the log.
  • Instead of overriding clone, a copy constructor (new User(other)) or a factory method is usually clearer.

On Java 16+, for a plain data-carrying class write a record, and equals, hashCode and toString come out right on their own:

public record Point(int x, int y) {}