← Back to Chapters

Java Object Class Methods

? Java Object Class Methods

? Quick Overview

In Java, the Object class is the root class of all classes. Every class automatically inherits methods from the Object class, even if it does not explicitly extend it.

? Key Concepts

  • Object class is present in java.lang package
  • All Java classes inherit from Object
  • Provides common utility methods
  • Methods can be overridden in subclasses

? Syntax / Theory

Some commonly used methods of the Object class are:

  • toString()
  • equals(Object obj)
  • hashCode()
  • getClass()
  • clone()
  • finalize()

? Code Example(s)

? View Code Example
// Demonstrating Object class methods
class Student {
    int id;
    String name;

    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public String toString() {
        return id + " " + name;
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student(1, "Rahul");
        Student s2 = new Student(1, "Rahul");

        System.out.println(s1.toString());
        System.out.println(s1.equals(s2));
        System.out.println(s1.getClass());
        System.out.println(s1.hashCode());
    }
}

? Live Output / Explanation

Output

1 Rahul
false
class Student
(Generated hash code value)

Explanation:

  • toString() returns object details
  • equals() compares reference by default
  • getClass() returns runtime class
  • hashCode() returns unique integer

 

? Interactive Lab: The "equals()" Trap

Enter data for two objects. See how equals() behaves with and without overriding.

Student s1

Student s2

Click "Run Comparison" to see results...

✅ Tips & Best Practices

  • Always override toString() for readable output
  • Override equals() and hashCode() together
  • Use getClass() for runtime type checks
  • Avoid using finalize() (deprecated)

? Try It Yourself

  • Override equals() to compare object values
  • Create two objects with same data and test equality
  • Print hash codes before and after overriding
  • Experiment with getClass() method