What is Object Class in Java: Explanation and Example
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
Object and how you can override toString() to customize the output.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()); } }
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
Objectclass is the parent of all Java classes. - It provides basic methods like
equals(),hashCode(), andtoString(). - You can override these methods to customize object behavior.
- Every Java object inherits these methods automatically.