The Object class is the root class of the Java class hierarchy, meaning every class in Java directly or indirectly inherits from it. It provides several built-in methods that support common operations such as object comparison, string representation, cloning, and thread synchronization.
Key Points: • Every Java class inherits methods from the Object class. • These methods provide default behavior that can be overridden when needed. • Methods like equals(), hashCode(), and toString() are frequently used in real-world applications. • Thread-related methods such as wait(), notify(), and notifyAll() support inter-thread communication. • Understanding Object class methods is essential for writing efficient and maintainable Java code.
Common Object Class Methods:
1. equals(Object obj) • Compares the contents or logical equality of two objects.
2. hashCode() • Returns a hash value for an object. • Commonly used in HashMap, HashSet, and other hash-based collections.
3. toString() • Returns a string representation of an object. • Often overridden to provide meaningful output.
4. clone() • Creates and returns a copy of an object. • Requires implementation of the Cloneable interface.
5. getClass() • Returns runtime class information of an object.
6. wait() • Causes the current thread to wait until notified.
7. notify() • Wakes up one waiting thread.
8. notifyAll() • Wakes up all waiting threads.
9. finalize() • Invoked by the Garbage Collector before object destruction. • Deprecated since Java 9 and should generally be avoided.
Example: When printing an object, Java internally calls the toString() method. Overriding it helps display meaningful information instead of the default memory reference.
Code Example:
class Employee {
private String name = "Amol";
@Override
public String toString() {
return "Employee{name='" + name + "'}";
}
}
public class Demo {
public static void main(String[] args) {
Employee emp = new Employee();
System.out.println(emp.toString());
System.out.println(emp.getClass().getName());
}
}Interview Tip: A concise interview answer is:
"The Object class is the parent of all Java classes and provides methods such as equals(), hashCode(), toString(), clone(), getClass(), wait(), notify(), and notifyAll(). These methods support object comparison, hashing, cloning, runtime type information, and thread coordination."