Skip to main content

Command Palette

Search for a command to run...

Object Class

Published
β€’7 min readβ€’View as Markdown

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?

PurposeDescription
Common behaviorGives every object a standard set of operations like equals, hashCode, toString, etc.
Polymorphism baseEnables generic programming and polymorphism.
InteroperabilityCollections, Frameworks, Reflection, Serialization use Object references.
Default implementationProvides default behavior that can be overridden in subclasses.

🧠 3️⃣ Methods of Object Class

MethodPurposeCommonly 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 objectOptional
protected void finalize()Called before object destruction (GC)Deprecated
public Class<?> getClass()Returns runtime class of objectNo
protected void finalize()Cleanup before GCDeprecated since Java 9
public void notify()Wakes a single thread waiting on object’s monitorNo
public void notifyAll()Wakes all waiting threadsNo
public void wait()Causes thread to waitNo
public void wait(long timeout)Waits with timeoutNo
public void wait(long timeout, int nanos)Waits with nanosecond precisionNo

🧩 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 calls notify().

  • 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
VariableReferenceHeap Object
e10xA{id=101, name=John}
e20xAsame as e1
e30xBdifferent object

βœ… == compares reference (0xA == 0xB ?)
βœ… equals() can compare logical data (id, name)


⚑ 6️⃣ Object Class in Frameworks

FrameworkUsage of Object Class
SeleniumWebElement inherits Object β†’ uses toString() in logs.
TestNGObject[][] used in @DataProvider for parameterization.
Collections FrameworkAll collections store Object references generically.
Reflection APIUses getClass() to inspect fields/methods.

🧩 7️⃣ Interview-Level Questions

🟒 Basic

  1. What is the superclass of all classes in Java?

  2. Can we override methods of Object class?

  3. What does toString() return by default?

  4. How are == and equals() different?

🟑 Intermediate

  1. Why should equals() and hashCode() be overridden together?

  2. What happens if hashCode() is not consistent with equals()?

  3. What is the difference between shallow and deep copy in clone()?

  4. What is the use of getClass()?

πŸ”΄ Advanced

  1. How is hashCode stored in memory (object header)?

  2. Can two unequal objects have same hashCode()?

  3. Why finalize() is deprecated?

  4. How does synchronization use wait() and notify() at the Object level?

  5. 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:

ConceptKey Point
Object classRoot 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

More from this blog

SS-JAVA

23 posts