Sobes.tech
Junior

What do you know about the Object class?

sobes.tech AI

Answer from AI

java.lang.Object is the root class in the Java class hierarchy. Every class implicitly inherits from Object.

Main methods:

  • equals(Object obj): Compares the current object with another object for equality. By default, compares references.
  • hashCode(): Returns the hash code of the object. Used in hash-based collections (e.g., HashMap, HashSet). If two objects are equal according to equals(), their hashCode() must be the same.
  • toString(): Returns a string representation of the object. By default, returns the class name + @ + hash code in hexadecimal format. Usually overridden to provide more informative output.
  • getClass(): Returns the Class object representing the runtime class of the object.
  • notify(): Resumes a thread waiting on this object's monitor.
  • notifyAll(): Resumes all threads waiting on this object's monitor.
  • wait() / wait(long timeout) / wait(long timeout, int nanos): Causes the current thread to wait until another thread calls notify() or notifyAll() on this object, or the specified timeout expires. Called only within synchronized blocks or methods.
  • clone(): Creates and returns a copy of this object. Requires implementation of the Cloneable interface.
  • finalize(): Called by the garbage collector before the object is removed. Not recommended for use due to unpredictability.

Example of overriding equals() and hashCode():

class Person {
    private String name;
    private int age;

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age &&
               Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

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

The Object class provides fundamental mechanisms necessary for working with objects in Java, such as comparison, hashing, thread synchronization, and obtaining class information.

What do you know about the Object class? — Java - sobes.tech