Object Class

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • The java.lang.Object class is the root of the class hierarchy in Java.
  • Every single class in Java directly or indirectly inherits from Object.
  • It provides essential methods that all Java objects share, such as toString(), equals(), and hashCode().

Concept

Because every class extends Object, a variable of type Object can hold a reference to any object in Java.

Key Methods of the Object Class

  1. public String toString(): Returns a string representation of the object.
  2. public boolean equals(Object obj): Compares the memory address of objects (by default).
  3. public int hashCode(): Returns a unique integer representing the memory address (by default).
  4. protected Object clone(): Creates and returns a copy of the object.
  5. public final Class<?> getClass(): Returns the runtime class object.
  6. wait(), notify(), notifyAll(): Used for thread synchronization.
  7. protected void finalize(): (Deprecated) Called by the garbage collector before destruction.

Examples

class MyClass {
    // Implicitly extends Object!
}

public class ObjectExample {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        
        // We get these methods for free because of the Object class!
        System.out.println(obj.toString()); // Output: MyClass@15db9742
        System.out.println(obj.hashCode()); // Output: 366712642
        
        // Polymorphism at the highest level
        Object genericObj = new MyClass();
        Object anotherObj = "I am a String";
        Object arrayObj = new int[5];
    }
}

Interview Questions

Q: Why are wait(), notify(), and notifyAll() defined in the Object class instead of the Thread class?
A: Because these methods operate on Object monitors (locks). In Java, every object has a lock associated with it. Threads wait for the lock of a specific object, not for another thread. Therefore, it makes architectural sense for the wait/notify mechanism to be tied to the Object itself rather than a Thread.

Q: What does the default implementation of toString() return?
A: It returns a string consisting of the class name, an @ symbol, and the unsigned hexadecimal representation of the object’s hash code (e.g., MyClass@15db9742). This is why it is almost always overridden in custom classes to return meaningful data.