Object Class
Excellent β understanding the Object class deeply is essential for interviews, OOP mastery, and automation framework design π
Letβs go step-by-step from What, Why, How, Internals, Real Examples, Memory-level explanation, and Interview + Coding questions.
π JAVA OBJECT CLASS β IN DEPTH
π§© 1οΈβ£ What is Object Class?
π The Object class is the parent (superclass) of all Java classes.
That means:
Every class in Java implicitly inherits from
Object, directly or indirectly.So, all objects in Java share a common set of methods defined in
Object.
π§ Syntax:
public class Object {
// defined in java.lang package
}
If you donβt explicitly extend any class:
class Employee {
// implicitly extends Object
}
Equivalent to:
class Employee extends Object {
}
π§© 2οΈβ£ Why Object Class Exists?
| Purpose | Description |
| Common behavior | Gives every object a standard set of operations like equals, hashCode, toString, etc. |
| Polymorphism base | Enables generic programming and polymorphism. |
| Interoperability | Collections, Frameworks, Reflection, Serialization use Object references. |
| Default implementation | Provides default behavior that can be overridden in subclasses. |
π§ 3οΈβ£ Methods of Object Class
| Method | Purpose | Commonly Overridden |
public String toString() | Returns string representation of object | β Yes |
public boolean equals(Object obj) | Compares two objects | β Yes |
public int hashCode() | Returns hash code value | β Yes |
protected Object clone() | Creates copy of the object | Optional |
protected void finalize() | Called before object destruction (GC) | Deprecated |
public Class<?> getClass() | Returns runtime class of object | No |
protected void finalize() | Cleanup before GC | Deprecated since Java 9 |
public void notify() | Wakes a single thread waiting on objectβs monitor | No |
public void notifyAll() | Wakes all waiting threads | No |
public void wait() | Causes thread to wait | No |
public void wait(long timeout) | Waits with timeout | No |
public void wait(long timeout, int nanos) | Waits with nanosecond precision | No |
π§© 4οΈβ£ Method Details with Examples
πΉ toString()
Purpose: Returns the object in string form (used in printing).
Default:
class Demo {}
public class Main {
public static void main(String[] args) {
Demo d = new Demo();
System.out.println(d.toString());
}
}
Output:
Demo@1a2b3c4d
π Default implementation = ClassName@hashCode_in_hex
Overriding:
class Employee {
int id; String name;
Employee(int id, String name){ this.id=id; this.name=name; }
@Override
public String toString(){
return "Employee[id="+id+", name="+name+"]";
}
}
public class Main {
public static void main(String[] args) {
Employee e = new Employee(101,"Rahul");
System.out.println(e);
}
}
Output:
Employee[id=101, name=Rahul]
β
Use toString() for logging, debugging, reporting (like in Extent Reports).
πΉ equals(Object obj)
Purpose: Compares two objects for logical equality.
Default behavior β compares memory addresses (==).
String s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1.equals(s2)); // true
System.out.println(s1 == s2); // false
Custom equals:
class Student {
int id;
Student(int id){ this.id=id; }
@Override
public boolean equals(Object obj){
if(this == obj) return true;
if(obj == null || getClass() != obj.getClass()) return false;
Student s = (Student)obj;
return id == s.id;
}
}
β This is used in Sets, Maps, and data comparisons.
πΉ hashCode()
Purpose: Returns integer hash code for object β used in hashing (HashMap, HashSet).
Default: returns memory address (converted to int).
Must Override with equals:
Whenever you override equals(), override hashCode() too.
@Override
public int hashCode() {
return Objects.hash(id);
}
β Ensures objects that are βequalβ have the same hashCode β avoids collisions in HashMap/HashSet.
πΉ getClass()
Purpose: Returns runtime class metadata.
Employee e = new Employee(1, "Ravi");
System.out.println(e.getClass().getName());
Output:Employee
β Used in reflection and frameworks (like Selenium, TestNG, Spring).
πΉ clone()
Purpose: Creates exact copy of an object (shallow copy by default).
class Emp implements Cloneable {
int id;
Emp(int id){ this.id=id; }
}
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Emp e1 = new Emp(10);
Emp e2 = (Emp)e1.clone();
System.out.println(e1.id + " " + e2.id);
}
}
β
Must implement Cloneable interface, else CloneNotSupportedException.
πΉ wait(), notify(), notifyAll()
Used for thread synchronization.
wait()β causes a thread to wait until another callsnotify().notify()β wakes one waiting thread.notifyAll()β wakes all waiting threads.
Used inside synchronized blocks only.
πΉ finalize()
Called by Garbage Collector before object is destroyed (cleanup).
β οΈ Deprecated in Java 9 β replaced by try-with-resources / cleaners.
βοΈ 5οΈβ£ Memory-Level Internals
Each object in Java memory (heap) has:
Header β hashcode, lock info (for synchronization)
Instance data β variables
Padding/alignment β 8 bytes alignment
Example:
Employee e1 = new Employee(101, "John");
Employee e2 = e1; // same reference
Employee e3 = new Employee(101, "John"); // new object
| Variable | Reference | Heap Object |
| e1 | 0xA | {id=101, name=John} |
| e2 | 0xA | same as e1 |
| e3 | 0xB | different object |
β
== compares reference (0xA == 0xB ?)
β
equals() can compare logical data (id, name)
β‘ 6οΈβ£ Object Class in Frameworks
| Framework | Usage of Object Class |
| Selenium | WebElement inherits Object β uses toString() in logs. |
| TestNG | Object[][] used in @DataProvider for parameterization. |
| Collections Framework | All collections store Object references generically. |
| Reflection API | Uses getClass() to inspect fields/methods. |
π§© 7οΈβ£ Interview-Level Questions
π’ Basic
What is the superclass of all classes in Java?
Can we override methods of Object class?
What does toString() return by default?
How are == and equals() different?
π‘ Intermediate
Why should equals() and hashCode() be overridden together?
What happens if hashCode() is not consistent with equals()?
What is the difference between shallow and deep copy in clone()?
What is the use of getClass()?
π΄ Advanced
How is hashCode stored in memory (object header)?
Can two unequal objects have same hashCode()?
Why finalize() is deprecated?
How does synchronization use wait() and notify() at the Object level?
How does Object equality affect HashSet or HashMap performance?
πͺ 8οΈβ£ Coding Practice
β Q1. Compare two Employee objects logically
class Employee {
int id;
String name;
Employee(int id, String name){
this.id = id; this.name = name;
}
@Override
public boolean equals(Object o){
if(this == o) return true;
if(o == null || getClass() != o.getClass()) return false;
Employee e = (Employee)o;
return id == e.id && name.equals(e.name);
}
@Override
public int hashCode(){
return Objects.hash(id, name);
}
}
β Q2. Custom toString() for better logging
@Override
public String toString(){
return "Employee{id=" + id + ", name='" + name + "'}";
}
β Q3. Cloning Example (Deep Copy)
class Address implements Cloneable {
String city;
Address(String city){ this.city = city; }
protected Object clone() throws CloneNotSupportedException { return super.clone(); }
}
class Person implements Cloneable {
String name;
Address addr;
Person(String name, Address addr){ this.name = name; this.addr = addr; }
protected Object clone() throws CloneNotSupportedException {
Person p = (Person) super.clone();
p.addr = (Address) addr.clone(); // deep copy
return p;
}
}
π§ 9οΈβ£ Key Notes for Interview:
| Concept | Key Point |
Object class | Root of all classes |
equals() | Logical equality |
hashCode() | Used in hashing (HashMap, HashSet) |
toString() | Debugging/logging |
clone() | Object copy |
wait()/notify() | Thread communication |
getClass() | Reflection |
finalize() | Deprecated cleanup method |
π§© π Summary Diagram
Object Class
ββββββββββ¬βββββββββββ¬βββββββββββ
β β β β
equals() hashCode() toString() clone()
β β β β
Logical Hashing Readable Copy
Compare Index Format Object