Senior
Tell me about the methods of the Object class in Java
sobes.tech AI
Answer from AI
In Java, the Object class is the root of the hierarchy of all classes. It contains basic methods that are inherited by all objects. Main methods:
equals(Object obj)— compares objects for equality. By default, it compares references, but it is often overridden to compare contents.hashCode()— returns the hash code of the object. It is important that ifequalsreturns true for two objects, theirhashCodeshould be the same.toString()— returns a string representation of the object. By default, it outputs the class name and hash code, but it is often overridden for convenient display.clone()— creates a copy of the object. It requires implementing theCloneableinterface.finalize()— called before garbage collection, but is deprecated and not recommended for use.getClass()— returns aClassobject describing the class of the object.notify(),notifyAll(),wait()— methods for working with the object's monitor in multithreading.
Example of overriding equals and hashCode:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyClass myClass = (MyClass) o;
return Objects.equals(field, myClass.field);
}
@Override
public int hashCode() {
return Objects.hash(field);
}