The Object class

The Object class in Java is one of the most fundamental concepts. Let’s break it down clearly.


🔑 What is the Object Class?

  • Object is the root superclass of all classes in Java.
  • Every class implicitly extends Object if it does not explicitly extend another class.
  • It is part of the java.lang package.
class MyClass { } // implicitly extends Object

🔎 Key Methods of Object Class

Here are the most commonly used methods:

MethodDescription
toString()Returns a string representation of the object (default is class name + hash code). Can be overridden.
equals(Object obj)Compares this object with another for equality. Default: compares references.
hashCode()Returns the hash code for the object. Often overridden with equals().
getClass()Returns the runtime class of the object.
clone()Creates and returns a copy of the object.
finalize()Called by GC before object is destroyed (deprecated in newer versions).
notify() / notifyAll() / wait()Used for thread communication in synchronized blocks.

🔧 Example 1: Using toString()

class Person {
    String name;

    Person(String name) {
        this.name = name;
    }

    // Override toString()
    public String toString() {
        return "Person name: " + name;
    }
}

public class ObjectExample {
    public static void main(String[] args) {
        Person p = new Person("Alice");
        System.out.println(p); // Automatically calls p.toString()
    }
}

✅ Output:

Person name: Alice

🔧 Example 2: Using equals() and hashCode()

class Person {
    String name;

    Person(String name) {
        this.name = name;
    }

    // Override equals
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Person person = (Person) obj;
        return name.equals(person.name);
    }

    // Override hashCode
    public int hashCode() {
        return name.hashCode();
    }
}

public class ObjectEqualsExample {
    public static void main(String[] args) {
        Person p1 = new Person("Alice");
        Person p2 = new Person("Alice");

        System.out.println(p1.equals(p2)); // true
        System.out.println(p1.hashCode() == p2.hashCode()); // true
    }
}

🔑 Key Points

  1. Every Java class inherits methods from Object.
  2. Methods like toString(), equals(), and hashCode() are meant to be overridden for meaningful behavior.
  3. Object is the foundation for polymorphism in Java, since any object can be referred to by type Object.
Object obj = new Person("Bob"); // Works because Person extends Object

✅ In short:

  • Object is the root of all Java classes.
  • It provides core functionality for object identity, equality, cloning, and runtime type info.

Leave a Reply