Course contentsShow
← Java
Lesson 543 of 2,87013. The Object Class and Common MethodsFree lesson

Implementing equals: The Step-by-Step Recipe

Master the standard pattern for overriding equals: null check, type check with instanceof, cast, and field-by-field comparison.

Implementing equals: The Step-by-Step Recipe

You'll learn the standard four-step pattern for correctly overriding equals in any Java class.

The Standard Recipe

While you've learned the five requirements for equals, implementing them follows a reliable, mechanical pattern. This recipe ensures you don't accidentally violate reflexivity, symmetry, transitivity, or consistency.

Step 1: Null Check

First, check if the parameter is null. By contract, equals must return false for null (nothing equals null except null itself, and this is never null).

if (obj == null) {
    return false;
}

Step 2: Type Check with instanceof

Use instanceof to verify the parameter is the correct type. This handles both type safety and the null check (since instanceof returns false for null).

if (!(obj instanceof Person)) {
    return false;
}

Modern shortcut: You can skip Step 1 entirely—instanceof handles it!

Step 3: Cast to the Correct Type

Once you've confirmed the type, cast the parameter so you can access its fields.

Person other = (Person) obj;

Step 4: Field-by-Field Comparison

Compare each significant field. For objects, use their equals method; for primitives, use ==.

return this.age == other.age && 
       this.name.equals(other.name);

Complete Example

@Override
public boolean equals(Object obj) {
    if (!(obj instanceof Person)) {
        return false;
    }
    Person other = (Person) obj;
    return this.age == other.age && this.name.equals(other.name);
}

Key Takeaway: The equals recipe is: instanceof check, cast, then compare fields—a pattern you'll repeat for virtually every class you write.