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
| Method | Signature | Purpose |
|---|---|---|
equals | boolean equals(Object obj) | Logical equality check (default is identity ==) |
hashCode | int hashCode() | Hash code value for hash tables |
toString | String toString() | Textual representation (ClassName@HexString) |
getClass | Class<?> getClass() | Runtime class metadata representation |
clone | protected Object clone() | Shallow field copy of the instance |
notify | void notify() | Wakes up a single thread waiting on this monitor |
notifyAll | void notifyAll() | Wakes up all threads waiting on this monitor |
wait (x3) | void wait() / wait(long) | Suspends thread execution on object monitor |
finalize | protected 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.