All topics
library
beginner

Object Class Methods

Know every method in java.lang.Object and when to override each one.

Every Java class implicitly extends Object, inheriting 11 methods. Interviewers frequently ask about the most important ones:

Object methods are like a government-issued ID card: everyone gets one by birth (inheritance). You can customize what's printed on it (override toString), but the card format (method signatures) is fixed.

Key Concepts

1
1. toString() — returns a string representation. Default: ClassName@hexHashCode. Override for meaningful output. Used by println, string concatenation, debuggers.
2
2. equals(Object) — tests logical equality. Default: reference equality (same as ==). Override when two distinct objects should be considered equal (same ID, same value). Must be reflexive, symmetric, transitive, consistent, and handle null.
3
3. hashCode() — returns an integer hash. Contract: equal objects must have equal hash codes. If you override equals, you must override hashCode. Violation breaks HashMap, HashSet.
4
4. clone() — creates a copy. Protected by default. Must implement Cloneable marker interface. Returns shallow copy — mutable fields share references. Prefer copy constructors or factory methods.
5
5. finalize() — called before GC. Deprecated since Java 9. Use try-with-resources and Cleaner instead. Unpredictable timing, performance cost, resurrection risk.
6
6. getClass() — returns runtime Class object. Final — cannot be overridden. Used in reflection.
7
7. wait(), notify(), notifyAll() — thread coordination on the object's monitor. Must be called inside synchronized block.