Compare `instanceof` vs `getClass()` for `equals` implementations
mainThere are two primary patterns for type checking in an equals method:
1. Using instanceof (Recommended)
This approach is compatible with the Liskov substitution principle and works well with frameworks like Hibernate or Mockito that use bytecode manipulation to create subclasses.
public boolean equals(Object obj) {
if (!(obj instanceof Foo)) return false;
// ...
}Note: instanceof handles null checks automatically.
2. Using getClass()
This approach ensures that only objects of the exact same class are considered equal. However, it causes equals to return false when comparing a base class instance to a subclass instance, even if the subclass adds no new state.
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass()) return false;
// ...
}// instanceof pattern
public boolean equals(Object obj) {
if (!(obj instanceof Foo)) return false;
// ...
}
// getClass pattern
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass()) return false;
// ...
}