Object Class
TL;DR
- The
java.lang.Objectclass 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(), andhashCode().
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
public String toString(): Returns a string representation of the object.public boolean equals(Object obj): Compares the memory address of objects (by default).public int hashCode(): Returns a unique integer representing the memory address (by default).protected Object clone(): Creates and returns a copy of the object.public final Class<?> getClass(): Returns the runtime class object.wait(),notify(),notifyAll(): Used for thread synchronization.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.