Object Class Methods

Thinking

Every class in Java implicitly inherits from the Object class, the root of the class hierarchy. This makes its methods universally available to all objects.

Understanding key methods like equals(), toString(), and hashCode() is vital for creating meaningful and well-behaved Java classes.

Description

The Object class in Java provides several important methods that are inherited by every Java class:

  • equals(Object obj): Compares this object with the specified object for equality.
  • toString(): Returns a string representation of the object.
  • hashCode(): Returns a hash code value for the object.
  • getClass(): Returns the runtime class of this object.
  • clone(): Creates and returns a copy of this object.
  • finalize(): Called by the garbage collector before the object is destroyed (deprecated in recent versions).

Overriding these methods helps define custom behaviors for objects in collections, logging, comparison, and debugging.

Video Resources

Examples (code)

Overriding equals() and toString()


class Student {
    int id;
    String name;

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

    @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 && name.equals(s.name);
    }

    @Override
    public String toString() {
        return "Student{id=" + id + ", name='" + name + "'}";
    }
}

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

        System.out.println(s1.equals(s2));   // true
        System.out.println(s1.toString());   // Student{id=101, name='Alice'}
    }
}
  

Real-World Applications

Object Comparison

Used in comparing instances logically, especially in data structures like HashSet and TreeSet.

Debugging

toString() helps in debugging by providing readable object details in logs.

Hash-based Collections

equals() and hashCode() must be overridden correctly to use objects as keys in HashMap.

Interview Questions

Q1: Why should you override the equals() method?

Show Answer

To allow logical comparison of object contents rather than their references.

Q2: What is the relationship between equals() and hashCode()?

Show Answer

If two objects are equal according to equals(), they must return the same hash code from hashCode(). This is critical for proper behavior in hash-based collections.

Q3: What does the toString() method return by default?

Show Answer

By default, toString() returns a string that includes the class name followed by the object's hash code in hexadecimal form.