Overriding equals: The Contract and Rules
What you'll learn: You'll understand the five formal requirements that every equals method must satisfy to work correctly in Java.
Why the Rules Matter
When you override equals (as we learned in lesson 288), you can't just write any comparison logic you want. Java defines a strict contract—a set of five rules—that your equals method must follow. If you break these rules, your objects won't work properly with collections, searching, or other Java features that rely on equality.
The Five Requirements
1. Reflexive
An object must equal itself:
x.equals(x) // must return true
2. Symmetric
If x equals y, then y must equal x:
x.equals(y) == y.equals(x) // must be true
3. Transitive
If x equals y and y equals z, then x must equal z:
// If x.equals(y) is true AND y.equals(z) is true
// Then x.equals(z) must also be true
4. Consistent
Multiple calls to equals must return the same result (assuming no object is modified):
x.equals(y) // always returns the same value
5. Null-Returning Behavior
Any object compared to null must return false:
x.equals(null) // must return false (never throw exception)
Think of It Like Math
These rules mirror mathematical equality: you'd never accept a math system where "A = B" is true but "B = A" is false. Java's equals contract ensures logical consistency across your entire program.
Key Takeaway: When overriding equals, you must satisfy all five rules: reflexive (self-equality), symmetric (bidirectional equality), transitive (chained equality), consistent (repeatable results), and null-safe (return false for null, never crash).