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.

published: reading time: 22 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

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() and hashCode() 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
    }
}
  • Implement Comparable when the class needs a natural ordering for sorting.
  • Use getClass() for an exact runtime-class check or instanceof when 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() and hashCode() 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

  1. Overriding equals() but not hashCode() — breaks HashMap/HashSet behavior
  2. Using mutable fields in equals/hashCode — object becomes “lost” in hash collections
  3. Forgetting to handle null fields — NullPointerException in equals
  4. Inconsistent symmetry — subclass equals must maintain parent’s contract
  5. 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 debugging
  • equals() — value-based equality for collections and comparisons
  • hashCode() — must be consistent with equals; used in hash collections
  • getClass() — final method that returns the runtime class; use instanceof when subtype checks are intended
  • clone() — protected shallow-copy API; Object.clone() requires Cloneable
  • finalize() — deprecated for removal; do not use it for resource cleanup
  • Contract: if a.equals(b) then a.hashCode() == b.hashCode() (always)
  • Records automatically generate all three with correct implementations

Interview Questions

1. What is the contract between equals() and hashCode()?
If two objects are equal according to `equals()`, they must have the same `hashCode()`. The reverse is not required — objects with the same hashCode may not be equal. This contract is essential for hash-based collections (HashMap, HashSet) to work correctly. Violating this contract causes objects to be "lost" in hash collections."

2. Why should you use Objects.equals() and Objects.hash()?
They handle null safely — `Objects.equals(a, b)` returns false if either is null, while `a.equals(b)` would throw NullPointerException. `Objects.hash(a, b, c)` creates a hash code from multiple fields without explicit null checks. Both make equals() and hashCode() implementations cleaner and less error-prone."

3. When should you NOT override equals()?
Don't override equals() when default reference equality (`==`) is correct — for example, for objects that represent unique resources like threads, input streams, or services where each instance is distinct by identity, not value. Also don't override for enums — they already have proper equals() and hashCode()."

4. What is the difference between getClass() and instanceof in equals()?
`getClass()` supports an exact-class equality policy: objects with different runtime classes cannot compare equal. `instanceof` admits subtype instances, which can fit an extensible equality model only when the full hierarchy preserves symmetry and transitivity. Choose the policy that matches the type's documented equality contract; neither check is universally safer."

5. What methods does Java automatically generate for records?
Records automatically generate `equals()`, `hashCode()`, `toString()`, and getters for all fields. The constructor is also generated that assigns all parameters to fields. The `x()` getter for field `x` (not `getX()`) is standard. Records are immutable and designed specifically for data carriers."

6. What is the relationship between hashCode and equals — can two objects have same hashCode but be unequal?
Yes — different objects can have the same hash code (hash collision). HashMap uses bucket index from hashCode, then equals to find exact entry within bucket. Contract: equal objects MUST have same hashCode; unequal can share hashCode."

7. Why should you not include mutable fields in equals and hashCode calculations?
If field used in hashCode changes after object is in a HashSet/HashMap, the object's hashCode changes. The object becomes "lost" — stored in bucket based on old hashCode, lookup uses new hashCode. Make fields final or use immutable types in equals/hashCode when possible."

8. What is the purpose of the toString() method and when should you override it?
toString() provides human-readable representation for debugging and logging. Default implementation returns ClassName@hexHash — not useful. Override to include meaningful field values that help identify the object in logs."

9. What is the clone() method and why is it generally not recommended?
`Object.clone()` is protected and makes a shallow copy of fields. It throws `CloneNotSupportedException` if the object's class does not implement `Cloneable`; mutable objects referenced by fields are not copied. A copy constructor or factory often makes the intended copy behavior clearer. See the Java SE 27 Object API.
10. What methods in Object are used for synchronization on the object itself?
wait(), notify(), notifyAll() — for thread synchronization on object monitor. These should only be called from synchronized context (synchronized method or block). Modern Java prefers higher-level concurrency utilities (java.util.concurrent)."

11. What is the finalize() method and why is it deprecated?
`Object.finalize()` is deprecated for removal and should not be used to release resources. Its timing is unpredictable, and finalization can be disabled. Use `AutoCloseable` with try-with-resources for deterministic cleanup; a `Cleaner` is a fallback for some non-heap resources. See JEP 421.
12. What is the difference between == and equals() for comparing objects?
For objects, `==` compares reference identity: whether both expressions refer to the same object. For primitives, it compares values. `equals()` uses the equality policy implemented by the class; use it for String content comparisons.

13. What is the hashCode contract in terms of equality of objects?
The `hashCode()` contract requires equal objects to have equal hash codes. Unequal objects may still share a hash code. If `hashCode()` is called repeatedly on the same object without changes to information used by `equals()`, it must return the same value during one execution. The `equals()` contract separately requires reflexivity, symmetry, transitivity, and consistency, and `x.equals(null)` must return `false`.

14. What is the equals-hashCode consistency rule for hash-based collections?
If a.equals(b) is true, then a.hashCode() must equal b.hashCode(). If hashCode differs, a cannot equal b — HashMap treats them as different keys. Violating this causes objects to be "lost" in hash collections (lookup fails)."

15. What is the difference between getClass() and instanceof in equals() implementation?
A `getClass()` check rejects equality across different runtime classes. An `instanceof` check admits subtype instances, but that alone does not preserve the `equals()` contract. If a subtype adds equality fields, the hierarchy must be designed to preserve symmetry and transitivity. Choose based on the equality policy the class promises."

16. What is the default behavior of hashCode() and can two unequal objects share a hash code?
`Object.hashCode()` is identity-based when not overridden, but the API does not promise a memory address or a distinct integer for every object. Unequal objects may share a hash code. The contract requires equal objects to have equal hash codes; it does not require the converse.
17. What is the relationship between Object class and the class hierarchy in Java?
Every Java class directly or indirectly extends `Object`. Its methods include `toString()`, `equals()`, `hashCode()`, `getClass()`, `clone()`, and the monitor methods `wait()`, `notify()`, and `notifyAll()`. `getClass()` is final, `clone()` is protected, and `finalize()` is deprecated for removal."

18. What happens when you use an object as a key in HashMap without overriding equals/hashCode?
The default `Object.equals()` compares reference identity, so two distinct objects are not equal just because their fields match. The default `hashCode()` is not computed from those fields, so a class that overrides `equals()` should also override `hashCode()`. Otherwise, lookup by an equal but distinct key in a hash-based collection is not reliable.
19. How does Java handle equals/hashCode for primitive wrapper types like Integer?
Integer overrides equals() to compare primitive values (Integer(5) equals Integer(5)). Integer cache for values -128 to 127 — same values may be same instances. For collections using Integer as key, value-based comparison works correctly."

20. Why should sensitive data not be included in toString() output?
toString() is used in logging, error messages, debug output — may be visible to unauthorized users. Password tokens, credit card numbers, or secrets in toString() can leak via logs. Create separate display method for sensitive data rather than including in toString()."

Further Reading

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.

#java-abstract-classes #java #java-fundamentals

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-arithmetic-operators #java #java-fundamentals

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.

#java-array-basics #java #java-fundamentals