0
0
JavaConceptBeginner · 3 min read

What is Object Class in Java: Explanation and Example

In Java, the Object class is the root class from which every other class inherits. It provides basic methods like equals(), hashCode(), and toString() that all Java objects share.
⚙️

How It Works

Think of the Object class as the great-grandparent of all classes in Java. Every class you create automatically inherits from Object, even if you don't write it explicitly. This means all objects share some common behaviors defined in Object.

For example, methods like equals() let you compare two objects to see if they are the same, while toString() gives a simple text description of the object. This is like having a basic set of tools that every object carries with it, so you don't have to build these tools from scratch each time.

💻

Example

This example shows how a simple class inherits methods from Object and how you can override toString() to customize the output.
java
public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person[name=" + name + ", age=" + age + "]";
    }

    public static void main(String[] args) {
        Person p = new Person("Alice", 30);
        System.out.println(p.toString());
    }
}
Output
Person[name=Alice, age=30]
🎯

When to Use

You use the Object class every time you create or work with objects in Java because it is the base of all classes. You might override its methods like equals() to define how two objects should be compared or hashCode() when using objects in collections like HashMap.

For example, when you want to print an object in a readable way, you override toString(). When you want to check if two objects represent the same data, you override equals(). These are common tasks in real-world Java programming.

Key Points

  • The Object class is the parent of all Java classes.
  • It provides basic methods like equals(), hashCode(), and toString().
  • You can override these methods to customize object behavior.
  • Every Java object inherits these methods automatically.

Key Takeaways

The Object class is the root of all classes in Java.
All Java objects inherit basic methods from Object automatically.
Override Object methods like toString() and equals() to customize behavior.
Using Object methods properly helps with object comparison and representation.