The Object class and its methods (toString, equals, hashCode, clone, finalize)
Every class in Java implicitly extends java.lang.Object. This means all objects inherit the methods of Object.
Commonly overridden methods:
toString()
Section titled “toString()”Returns a string representation of the object. Default: ClassName@hashcode.
@Overridepublic String toString() { return "Person{name='" + name + "', age=" + age + "}";}equals(Object obj)
Section titled “equals(Object obj)”Compares objects for equality. Default: reference equality (==).
@Overridepublic boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Person p = (Person) obj; return age == p.age && name.equals(p.name);}hashCode()
Section titled “hashCode()”Returns an integer hash code. Must be consistent with equals: if a.equals(b) then a.hashCode() == b.hashCode().
@Overridepublic int hashCode() { return Objects.hash(name, age);}clone()
Section titled “clone()”Creates and returns a copy of the object. Requires implementing Cloneable interface.
@Overrideprotected Object clone() throws CloneNotSupportedException { return super.clone(); // shallow copy}finalize()
Section titled “finalize()”Called before garbage collection (deprecated since Java 9). Do not use.
Best practices:
- Always override
toString()for meaningful object representation. - Override
equals()andhashCode()together (e.g., for use in collections likeHashMap). - Prefer
Objects.equals()andObjects.hash()to avoid null checks.