Sobes.tech
Junior — Middle

Can you list and describe the main methods of the Object class in Java?

sobes.tech AI

Answer from AI

Main methods of the Object class in Java, inherited by all objects:

  • equals(Object obj) — compares the current object with another for equality. By default, compares references, but often overridden to compare contents.

  • hashCode() — returns the hash code of the object, used in collections like HashMap, HashSet. When overriding equals, hashCode should also be overridden.

  • toString() — returns a string representation of the object. By default, outputs the class name and hash code, often overridden for convenient display.

  • clone() — creates and returns a copy of the object. Requires implementation of the Cloneable interface and is usually overridden.

  • finalize() — called before garbage collection, used for resource release (deprecated method, not recommended for use).

  • getClass() — returns the Class object describing the class of the object.

  • wait(), notify(), notifyAll() — methods for thread work and synchronization.

Example of overriding equals and hashCode:

@Override
public boolean equals(Object obj) {
    if (this == obj) return true;
    if (obj == null || getClass() != obj.getClass()) return false;
    MyClass other = (MyClass) obj;
    return this.id == other.id;
}

@Override
public int hashCode() {
    return Objects.hash(id);
}
Can you list and describe the main methods of the… - sobes.tech