Skip to main content

2.7 java.lang.Object Core Methods

← Back to Chapter 2: Java Overview & Memory Model

java.lang.Object sits at the very apex of the Java class hierarchy. Every class in Java is an indirect or direct subclass of Object, inheriting 11 foundational methods.


1. Summary of All 11 Methods​

MethodSignaturePurpose
equalsboolean equals(Object obj)Logical equality check (default is identity ==)
hashCodeint hashCode()Hash code value for hash tables
toStringString toString()Textual representation (ClassName@HexString)
getClassClass<?> getClass()Runtime class metadata representation
cloneprotected Object clone()Shallow field copy of the instance
notifyvoid notify()Wakes up a single thread waiting on this monitor
notifyAllvoid notifyAll()Wakes up all threads waiting on this monitor
wait (x3)void wait() / wait(long)Suspends thread execution on object monitor
finalizeprotected void finalize()Deprecated in Java 9, removed in 18 (Unreliable GC cleanup)

2. Shallow Copy vs Deep Copy with clone()​

The default implementation of Object.clone() performs a Shallow Copy:

  • Primitives are duplicated by value.
  • Object references are copied by memory address (both original and clone point to the identical nested objects).
public class User implements Cloneable {
private String name;
private Address address; // Mutable reference

@Override
public User clone() {
try {
User cloned = (User) super.clone();
// To achieve DEEP COPY, nested mutable objects must also be cloned:
cloned.address = new Address(this.address.getCity());
return cloned;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
Recommendation: Copy Constructors

Modern Java prefers Copy Constructors (public User(User other) { ... }) or Factory methods over the fragile Cloneable interface.