Object Class in Java
java.lang.Object is the ultimate superclass of every class in Java. Whether you define class MyClass or class MyClass extends SomeOtherClass, the inheritan...
The Root of Every Java Class
java.lang.Object is the ultimate superclass of every class in Java. Whether you define class MyClass or class MyClass extends SomeOtherClass, the inheritance chain always ends at Object. This means every Java object—regardless of which package it comes from or how it was designed—inherits a common set of methods from Object. These methods establish a baseline contract that all Java objects can fulfill.
The Core Methods of Object toString() returns a string representation of the object. The default implementation returns the class name plus the hash code in hexadecimal, which is rarely useful, so most classes override it. equals(Object obj) tests logical equality; the default implementation tests reference identity (same as ==). hashCode() returns an integer used in hash-based collections like HashMap. The contract requires that if equals() returns true for two objects, they must return the same hashCode().
equals and hashCode Must Stay in Sync If you override equals() to compare fields, you must also override hashCode() to be consistent. Violating this contract produces bizarre behavior in collections: you might put a key into a HashMap and then be unable to retrieve it because the key's hash code changed or two equal objects hash to different buckets. Modern IDEs and libraries like Lombok can generate consistent equals/hashCode pairs to avoid manual mistakes.
Other Notable Object Methods getClass() returns the runtime Class object, useful for reflection. clone() produces a shallow copy but requires implementing Cloneable—a pattern now considered dated in favor of copy constructors. wait(), notify(), and notifyAll() are used in low-level thread synchronization and work because every Object has an intrinsic monitor lock. finalize() was deprecated in Java 9 and removed later; use try-with-resources or Cleaners for resource cleanup instead.
Code Example: class Book { String title; Book(String title) { this.title = title; }
@Override public String toString() { return "Book[" + title + "]"; }
@Override public boolean equals(Object o) { if (!(o instanceof Book)) return false; return title.equals(((Book) o).title); }
@Override public int hashCode() { return title.hashCode(); } }
Book b1 = new Book("Dune"); Book b2 = new Book("Dune"); System.out.println(b1.equals(b2)); // true System.out.println(b1); // Book[Dune]
Interview Tip: The equals-hashCode contract is one of the most commonly tested topics in Java interviews. Frame your answer around the HashMap use case: if two objects are equal but have different hash codes, a HashMap will store them in different buckets and fail to find one when looking up the other. This scenario makes the abstract contract concrete and memorable.