The Object Class in Java
Learn Java Object methods for string output, equality, hashing, cloning, runtime type checks, and why finalization is deprecated for removal.
Learn Java Object methods for string output, equality, hashing, cloning, runtime type checks, and why finalization is deprecated for removal.
The Object Class in Java
Every class in Java directly or indirectly extends Object. It provides the base contract that all objects fulfill — identity, equality, representation, and class information.
Introduction
Every class in Java directly or indirectly extends java.lang.Object. Its methods include toString(), equals(), hashCode(), getClass(), clone(), finalize(), and the object-monitor methods wait(), notify(), and notifyAll(). Their access and lifecycle rules differ: getClass() is final, clone() is protected, and finalize() is deprecated for removal.
The methods most commonly overridden are toString(), equals(), and hashCode(). The default toString() prints the class name and a hash-based value, which is rarely a useful log message. For hash-based collections, equal objects must have the same hash code. Violating that contract can make an entry hard to find with an equal key.
This post covers when and how to override toString(), equals(), and hashCode() correctly, including the symmetry and transitivity requirements of the equals contract, the use of Objects.equals() and Objects.hash() for cleaner implementations, and the tradeoffs between getClass()-based and instanceof-based equality. It also covers getClass() for runtime type inspection, why clone() is generally avoided, and how records (Java 16+) automatically generate correct implementations of all three methods with zero boilerplate.
Object methods to override
Override Object methods when:
- Meaningful string representation needed — custom
toString()for debugging - Value-based equality needed — custom
equals()andhashCode()for collections
Natural ordering comes from Comparable, a separate interface. getClass() and instanceof are application choices for type checks. Use explicit authorization logic for security decisions.
public final class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Point{x=" + x + ", y=" + y + "}";
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true; // Same reference
if (!(obj instanceof Point other)) return false; // Different type
return x == other.x && y == other.y; // Value equality
}
@Override
public int hashCode() {
return 31 * x + y; // Consistent with equals
}
}
Related application choices
- Implement
Comparablewhen the class needs a natural ordering for sorting. - Use
getClass()for an exact runtime-class check orinstanceofwhen subtype instances should match the tested type. - For security decisions, use access controls and authorization checks rather than runtime type checks.
When not to override
Don’t override when:
- Default behavior is sufficient — Object’s toString() prints class@hash
- Simplicity is preferred — for throwaway DTOs or simple records
- Identity comparison only — default equals() uses
==which may be correct - Hashing is on a measured hot path — profile before considering cached hash codes
Object Methods — Mermaid Diagram
classDiagram
class Object {
+toString() String
+equals(Object) boolean
+hashCode() int
+getClass() Class~?~
#clone() Object
#finalize() void
+notify() void
+notifyAll() void
+wait(long) void
}
note for Object "Every class extends Object either directly or through a chain"
Current API notes for clone() and finalize()
Object.clone() is protected. Its implementation makes a shallow copy of the fields, so referenced objects are shared unless the class copies them separately. The call throws CloneNotSupportedException unless the object’s class implements the marker interface Cloneable. A copy constructor or factory can make the copy semantics easier to follow. If a class overrides clone(), it should document whether mutable fields are shared or copied.
Object.finalize() is deprecated for removal. Its timing is unpredictable, it may never run when finalization is disabled, and it should not manage resources. Use AutoCloseable with try-with-resources for deterministic cleanup. A Cleaner can handle some fallback cleanup after an object becomes unreachable, but it does not guarantee when cleanup runs. See the Java SE 27 Object API and JEP 421.
Failure Scenarios
1. Breaking the equals-hashCode Contract
The equals-hashCode contract says that whenever a.equals(b) is true, a.hashCode() must equal b.hashCode(). The Java API makes this mandatory, and HashMap and HashSet rely on it to find entries. Override equals() without overriding hashCode(), and equal instances are not guaranteed to have matching hash codes, so lookup by an equal key can fail.
The Broken class below shows the contract problem. It overrides equals() to compare value fields but leaves hashCode() inherited from Object, which does not compute a hash from value. Equal instances therefore are not guaranteed to have equal hash codes. A lookup with a logically equal key may fail; the API does not promise that distinct objects always get distinct hash codes, so the exact result is not portable.
public class Broken {
private String value;
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Broken other)) return false;
return this.value.equals(other.value);
}
// MISSING: hashCode override — breaks HashMap, HashSet contracts!
}
// Usage breaks HashMap
Broken a = new Broken();
a.value = "test";
Broken b = new Broken();
b.value = "test";
Map<Broken, Integer> map = new HashMap<>();
map.put(a, 1);
System.out.println(map.get(b)); // May fail because hashCode is not overridden
2. Using Mutable Fields in hashCode
Even with a correct hashCode() override, using mutable fields in its calculation creates a second failure mode. A hash code must stay consistent for as long as an object lives in a hash-based collection. If a field used in hashCode() changes after the object is inside a HashSet or HashMap, the object’s hash code changes. The entry ends up in the wrong bucket — stored under the old hash code but looked up under the new one.
The Mutable class below uses name in its hashCode() calculation. After adding the object to a HashSet, changing name from “Alice” to “Bob” changes the hash code. The object is now lost in the set. Calling set.contains(obj) may return false, and you can never remove it by value — only by iterator. This is not a collection bug; it is the expected behavior given what you told the collection about where to find the object.
The solution is to use immutable fields in hashCode(). Declare fields as final, or don’t include mutable fields in the calculation. If you must use mutable state, rebuild the collection after any mutation — immutability is the cleaner path.
public class Mutable {
private String name;
@Override
public int hashCode() {
return name.hashCode(); // PROBLEM: if name changes, hashCode changes!
}
}
Mutable obj = new Mutable();
obj.name = "Alice";
Set<Mutable> set = new HashSet<>();
set.add(obj);
obj.name = "Bob"; // HashCode changed while in HashSet — may be lost!
3. equals() with Incorrect Symmetry
The equals() contract has three properties: reflexive (x.equals(x) is always true), symmetric (x.equals(y) implies y.equals(x)), and transitive (x.equals(y) and y.equals(z) implies x.equals(z)). Symmetry is the one that inheritance breaks most often. When a subclass adds fields to the equality check, it is easy to write an equals() that gives different results depending on which object comes first.
The Parent and Child classes below show this. Parent.equals(Child) checks only the value field — since Child inherits value, a Parent and a Child with the same value are considered equal. But Child.equals(Parent) calls the parent’s equals first, then also requires extra to match — and extra does not exist in Parent. The two calls disagree: p.equals(c) returns true while c.equals(p) returns false. Symmetry violated.
The problem is that Child’s equals() adds a condition that Parent cannot satisfy. One option is an exact-class policy with getClass(), which rejects equality between Parent and Child. An extensible equality model can use instanceof, but every class in the hierarchy must follow a design that preserves symmetry and transitivity.
public class Parent {
private int value;
@Override public boolean equals(Object obj) {
return obj instanceof Parent && ((Parent) obj).value == this.value;
}
}
public class Child extends Parent {
private String extra;
@Override public boolean equals(Object obj) {
// Violates symmetry: Parent.equals(Child) vs Child.equals(Parent)
if (!super.equals(obj)) return false;
return obj instanceof Child && ((Child) obj).extra.equals(this.extra);
}
}
Parent p = new Parent();
Child c = new Child();
p.equals(c) != c.equals(p) // Symmetry broken!
Trade-off Table
| Member | Default behavior or API detail | Guidance |
|---|---|---|
toString() |
ClassName@hashcode |
Override for useful diagnostic output |
equals() |
== (reference equality) |
Override when the class has value-based equality |
hashCode() |
Object identity hash code | Keep it consistent with equals() for hash-based collections |
clone() |
Protected shallow copy; may throw CloneNotSupportedException |
Usually prefer a copy constructor or factory |
getClass() |
Final; returns the runtime Class object |
Call when exact runtime-class identity matters |
finalize() |
Deprecated for removal | Do not use for cleanup; choose an explicit resource lifecycle |
Code Snippets
Complete equals/hashCode Implementation
The Employee class below is a production-quality implementation of equals(), hashCode(), and toString() following the standard JDK pattern.
The equals() method starts with this == obj, then applies this class’s exact-runtime-class policy: obj == null || getClass() != obj.getClass(). That policy means an Employee instance cannot compare equal to a subclass instance. It is one valid choice when the equality contract excludes subclasses. After the type check, a safe cast is valid and the method compares all three fields. The null check for name uses the ternary name == null ? other.name == null : name.equals(other.name) to avoid a NullPointerException if name is null.
The hashCode() uses the standard 31 multiplier. 31 is an odd prime chosen historically for producing well-distributed hash codes for field combinations. The calculation: start with id’s hash code, then for each field multiply the running result by 31 and add the field’s hash code (or 0 for null). The final value is consistent with equals() because every field that participates in equals() also feeds into hashCode().
public class Employee {
private final String id;
private final String name;
private final int departmentCode;
public Employee(String id, String name, int departmentCode) {
this.id = id;
this.name = name;
this.departmentCode = departmentCode;
}
// equals following Java best practices
@Override
public boolean equals(Object obj) {
if (this == obj) return true; // Same reference — fastest check
if (obj == null || getClass() != obj.getClass()) return false; // Type check
Employee other = (Employee) obj; // Safe cast after type check
return id.equals(other.id) &&
(name == null ? other.name == null : name.equals(other.name)) &&
departmentCode == other.departmentCode;
}
// hashCode consistent with equals
@Override
public int hashCode() {
int result = id.hashCode();
result = 31 * result + (name == null ? 0 : name.hashCode());
result = 31 * result + departmentCode;
return result;
}
// toString for debugging
@Override
public String toString() {
return "Employee{id='" + id + "', name='" + name + "', departmentCode=" + departmentCode + "}";
}
}
getClass() versus instanceof
getClass() and instanceof answer different questions. a.getClass() == b.getClass() is true only when both references point to objects with the same runtime class. value instanceof Type is true when the value refers to an instance of Type or one of its subtypes.
In equals(), a getClass() check sets an exact-class policy: a base-class instance and subclass instance cannot compare equal. This fits classes that do not allow equality across runtime types, including final value classes. It is restrictive for an extensible base class.
An instanceof check admits subtype instances. It can work in an extensible equality design when the hierarchy shares a coherent equality contract. If a subclass adds state to equality, a simple instanceof check can break symmetry, as the earlier example shows. Java 16+ pattern matching (instanceof Car car) also binds a variable with the tested type.
Choose the check that matches the class’s documented equality contract. Use getClass() if instances of different runtime classes must not compare equal. Use instanceof only when subtype equality is intended and the hierarchy can preserve symmetry and transitivity. Neither policy is right for every class.
class Vehicle { }
class Car extends Vehicle {
void drive() { System.out.println("Driving"); }
}
class SportCar extends Car { }
class Truck extends Vehicle { }
class TypeCheckExample {
public static void main(String[] args) {
Vehicle v1 = new SportCar();
// Subtype check: true for SportCar because it extends Car.
if (v1 instanceof Car car) {
car.drive();
}
// Exact class check: false for SportCar.
if (v1.getClass() == Car.class) {
System.out.println("Exact Car instance");
}
}
}
This example uses pattern matching for instanceof, available since Java 16. Expected output:
Driving
Records and equals/hashCode (Java 16+)
Records were introduced in Java 16 as concise data carriers. A record like record Point(int x, int y) has final component fields, and the compiler generates equals(), hashCode(), toString(), and accessors such as x() and y(). This is shallow immutability: a record component can still refer to a mutable object.
Records are implicitly final, so their generated equals() compares values only with instances of the same record class. The generated hashCode() and toString() follow the record component model as well.
The equivalent manual implementation below shows exactly what the compiler generates. getClass() for the type check, the same null-safe field comparisons, the same 31-multiplier formula for hashCode(). Records do not add hidden behavior — they eliminate the boilerplate and the risk of getting it wrong.
For a class that mainly carries named data and does not need a different identity or mutability policy, a record may fit. Use a regular class when its lifecycle or invariants need more control.
// Records automatically generate equals, hashCode, toString
public record Point(int x, int y) {}
// Is equivalent to:
public final class Point {
private final int x;
private final int y;
public Point(int x, int y) { this.x = x; this.y = y; }
public int x() { return x; }
public int y() { return y; }
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Point other = (Point) obj;
return x == other.x && y == other.y;
}
public int hashCode() {
return 31 * x + y;
}
public String toString() {
return "Point[x=" + x + ", y=" + y + "]";
}
}
Observability Checklist
-
equals()andhashCode()overridden together — never one without the other - Both use the same fields (the “equality fields”)
-
equals()handles null and same-class check first -
hashCode()consistent across object’s lifetime (immutable fields preferred) -
toString()provides useful debug information without exposing sensitive data
Security Notes
- Don’t put sensitive data in toString() — logs may expose passwords, tokens
- Defensive copies in equals() — don’t modify objects during comparison
- Don’t use getClass() for security decisions — use proper access control instead
- hashCode() for security-sensitive objects — may be used in hash-based collections
public final class SecureToken {
private final char[] secret;
@Override
public String toString() {
// NEVER expose secret in toString!
return "SecureToken[id=" + id + "]"; // Safe — no secret
}
@Override
public boolean equals(Object obj) {
// Defensive: compare without exposing secret
if (this == obj) return true;
if (!(obj instanceof SecureToken other)) return false;
return Arrays.equals(this.secret, other.secret); // char[] comparison
}
@Override
public int hashCode() {
// For char[], must iterate to create hash
return Arrays.hashCode(secret);
}
}
Pitfalls
- Overriding equals() but not hashCode() — breaks HashMap/HashSet behavior
- Using mutable fields in equals/hashCode — object becomes “lost” in hash collections
- Forgetting to handle null fields — NullPointerException in equals
- Inconsistent symmetry — subclass equals must maintain parent’s contract
- Overly complex equals — consider using Objects.equals() and Objects.hash()
// Clean equals/hashCode using Objects utility
public final class CleanPerson {
private final String name;
private final int age;
@Override
public boolean equals(Object obj) {
return obj instanceof CleanPerson other &&
Objects.equals(name, other.name) &&
age == other.age;
}
@Override
public int hashCode() {
return Objects.hash(name, age); // Cleaner than manual calculation
}
}
Quick Recap
toString()— human-readable representation; override for debuggingequals()— value-based equality for collections and comparisonshashCode()— must be consistent with equals; used in hash collectionsgetClass()— final method that returns the runtime class; useinstanceofwhen subtype checks are intendedclone()— protected shallow-copy API;Object.clone()requiresCloneablefinalize()— deprecated for removal; do not use it for resource cleanup- Contract: if
a.equals(b)thena.hashCode() == b.hashCode()(always) - Records automatically generate all three with correct implementations
Interview Questions
Further Reading
- Classes and Objects — object instantiation fundamentals
- Inheritance in Java — extends keyword and class hierarchy
- Interfaces in Java — contracts via Object-compatible interfaces
- Java SE 27 Object API — current method contracts and deprecation notes
- JEP 421 — why finalization is deprecated for removal and cleanup alternatives
Conclusion
Every class in Java ultimately inherits from Object, either directly or through a chain of superclasses. This makes Object the root of the entire type hierarchy and its methods the common contract that all objects share. Understanding Object’s methods is essential for writing Java code that integrates properly with collections, streams, and the broader JDK ecosystem.
The Object methods most often overridden are toString(), equals(), and hashCode(). getClass() is final, so it cannot be overridden; call it when an exact runtime-class check is part of the equality policy. Use instanceof when subtype matches are intended, provided the equality design preserves symmetry and transitivity.
The equals() and hashCode() contract requires equal objects to have the same hash code. A HashMap uses the hash to find candidate entries, then calls equals(); if equal objects have different hashes, lookup by the other key can miss the entry.
Object.clone() is protected and performs a shallow copy unless the class copies mutable fields itself; it also requires Cloneable. Prefer an explicit copy constructor or factory when that better communicates what the copy contains. Object.finalize() is deprecated for removal and should not be used for cleanup. Use try-with-resources for resources with a defined lifetime.
Records (Java 16+) automate equals(), hashCode(), and toString() generation for immutable data carriers. A record Point(int x, int y) is semantically equivalent to a manually written immutable class with those methods, but with zero boilerplate. Records connect to the broader OOP model through the classes and objects concepts (detailed in Classes and Objects) — they are simply a cleaner way to define simple data-holding classes that integrate properly with Java’s object system.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.