Middle
What methods does the Object class contain?
sobes.tech AI
Answer from AI
In Java, the Object class is the root class for all classes. It contains several key methods that are inherited by all objects:
equals(Object obj)— compares the current object with another for equality.hashCode()— returns the hash code of the object, used in collections.toString()— returns a string representation of the object.getClass()— returns the Class object describing the class of the object.clone()— creates a copy of the object (requires implementation of the Cloneable interface).finalize()— called before garbage collection (deprecated method).wait(),notify(),notifyAll()— methods for thread work and synchronization.
Example of overriding the equals and hashCode methods:
@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);
}