Sub topic 12
Overload versus override: a common equals bug
This chapter assumes you can write Java classes with fields and constructors. It also assumes you know what method overriding is, and that you have used List, Set, and Map. The chapter covers a single mistake: declaring an equals method that looks right but does not replace Object.equals. The class compiles, simple tests may pass, and collections still behave wrongly.
The bug
Object declares this method:
public boolean equals(Object obj)A class overrides it only if its method has the same name and the same parameter types. The parameter type must be exactly Object. A method with the same name but a different parameter type is an overload, which is a separate method that sits next to the inherited one.
Many developers write the overload by accident, because the class they are comparing feels like the natural parameter type:
public boolean equals(Id other) // overload, not overrideThe class now has two equals methods: the inherited equals(Object), which compares identity, and the new equals(Id). The compiler accepts both.
Seeing the failure
This program is complete and runs as shown.
import java.util.List;
public class OverloadDemo {
static final class Id {
final int value;
Id(int value) {
this.value = value;
}
// Overload, not override: the parameter type is Id, not Object
public boolean equals(Id other) {
return other != null && value == other.value;
}
}
public static void main(String[] args) {
Id a = new Id(1);
Id b = new Id(1);
Object o = b;
System.out.println(a.equals(b)); // true
System.out.println(a.equals(o)); // false
System.out.println(List.of(a).contains(b)); // false
}
}The same two objects give different answers depending on how the argument is declared. The first call passes an Id, so the overload runs. The second passes the same object through a variable of type Object, so the inherited method runs. It compares references, and a and b are different objects.
Why it happens: two different decisions
Java makes two separate choices when you call a method.
- At compile time, the compiler picks a method signature. It uses the declared (static) type of the argument expression. This step is overload resolution.
- At run time, the JVM picks which class's implementation of that signature to run. It uses the actual type of the receiver object. This step is dynamic dispatch, and only overriding takes part in it.
Collections such as List, HashSet, and HashMap were compiled long before your class existed. Their code calls equals on values typed as Object, so the compiler selected equals(Object) for them. Dynamic dispatch then looks for an override of equals(Object) in your class. It finds none, because your equals(Id) has a different signature, so Object.equals runs.
Where each call goes
| Call | Declared type of argument | Method selected | Result for two `Id(1)` objects |
|---|---|---|---|
| `a.equals(b)` | `Id` | `equals(Id)`, your overload | `true` |
| `a.equals(o)` | `Object` | `equals(Object)`, inherited | `false` |
| `list.contains(b)` | `Object` inside the library | `equals(Object)`, inherited | `false` |
| `set.contains(b)` | `Object` inside the library | `hashCode()` then `equals(Object)`, both inherited | `false` |
Code that calls your overload directly with the exact type will pass, and so will many hand-written unit tests. Failures show up only when the object goes through a library, a generic method, or a variable typed as Object. Such failures are hard to trace.
The fix: `@Override`
Add @Override to every method you intend to override. The annotation asks the compiler to check that a method with that exact signature exists in a supertype. If it does not, compilation fails.
static final class Id {
final int value;
Id(int value) {
this.value = value;
}
@Override // compile error: method does not override or implement a method from a supertype
public boolean equals(Id other) {
return other != null && value == other.value;
}
}The compiler reports the error on the @Override line, and the mistake never reaches a test. Fix it by changing the parameter type to Object and checking the type inside the method:
import java.util.Objects;
public class FixedDemo {
static final class Id {
final int value;
Id(int value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Id)) return false;
Id other = (Id) o;
return value == other.value;
}
@Override
public int hashCode() {
return Objects.hash(value);
}
}
public static void main(String[] args) {
Id a = new Id(1);
Object o = new Id(1);
System.out.println(a.equals(o)); // true
System.out.println(java.util.Set.of(a).contains(new Id(1))); // true
}
}The instanceof test is needed because the parameter is now an Object. It also rejects null, because null instanceof Id is false. Defining hashCode in the same change keeps the two methods consistent, which the hash-collections chapters explain.
The same trap in other methods
The mistake is not limited to equals. Any method whose name matches but whose signature differs creates a new method instead of replacing the inherited one.
| What you wrote | Why it does not override | Effect |
|---|---|---|
| `public boolean equals(Id other)` | Parameter type is not `Object` | Collections use identity comparison |
| `public boolean equals(Object o, int mode)` | Extra parameter | Never called by library code |
| `public boolean Equals(Object o)` | Capital `E`, so a different name | Never called by library code |
| `public int hashcode()` | Lowercase `c`, so a different name | Hash codes remain identity-based |
| `public String tostring()` | Lowercase `s`, so a different name | Printing shows `Id@1b6d3586` style text |
| `public static boolean equals(Object o)` | Static methods hide, not override | Compile error: a static method cannot hide an instance method |
| `boolean equals(Object o)` | Weaker access than `public` | Compile error: attempting to assign weaker access privileges |
Misspelled names are the nastiest of these, because there is no compile error without @Override. A class with hashcode() and a correct equals(Object) looks complete, yet it still has the "equal objects, different hash codes" bug.
Finding the bug without `@Override`
If you inherit code that lacks annotations, three checks help:
- IDE inspections flag a method named
equalswhose parameter is notObject. IntelliJ IDEA reports this as a "covariant equals" style warning. - Static analysis tools such as Error Prone and SpotBugs include checks for this pattern. SpotBugs reports it as "Covariant equals".
- A contract test that passes the object through
Objectvariables catches it. For example,assertEquals(a, b)in JUnit takes twoObjectarguments, so it exercisesequals(Object). The testing chapter returns to this.
You can also check by reflection which method your class declares:
import java.lang.reflect.Method;
public class WhichEquals {
public static void main(String[] args) {
for (Method m : OverloadDemo.Id.class.getDeclaredMethods()) {
if (m.getName().equals("equals")) {
System.out.println(m);
}
}
}
}Run in the same package as OverloadDemo, it prints a single equals whose parameter type is Id. A correct class would show java.lang.Object there.
Common questions
Can the parameter type be a more specific type if I want? No. Parameter types must match exactly to override. Return types can be covariant (narrower), but equals returns boolean, a primitive, so that does not apply. Parameter types cannot be narrowed.
Do generics change this? Only in generic supertypes you define yourself. Object.equals is not generic, so equals(T other) in a generic class is still an overload, because T erases to Object only if unbounded. Do not rely on erasure. Write equals(Object).
Do records have this problem? A record generates a correct equals(Object). If you declare an equals in a record, the same rules apply, and @Override is still the safeguard.
Exercise
A class declares public boolean equals(Order other) and no hashCode. It compiles. Calling orders.contains(new Order(5)) on a List<Order> that holds an equal order returns false. Explain why, and name the one-line change that makes the compiler reveal the mistake.
Show answer
List.contains is compiled against Object, so it calls equals(Object). Order does not override that method, because equals(Order) has a different parameter type and is only an overload. The inherited Object.equals runs and compares references, so two separate Order objects are not equal. Adding @Override above equals(Order other) makes the compiler fail with "method does not override or implement a method from a supertype". The real fix is to change the parameter to Object, check with instanceof Order, and add a matching hashCode.
Exercise
Which of these declarations override a method inherited from Object? (a) public int hashCode() (b) public int hashcode() (c) public String toString() (d) public boolean equals(Object a, Object b)
Show answer
Only (a) and (c). (b) differs in case, so it is a new method named hashcode. (d) has two parameters, so it is an unrelated overload.