I have an interface and I want everyone who implements this interface to implements an overrridden \"equals\" method.
Is there a way to make sure that happens?
No, you only can create an abstract class instead of an interface like this:
public abstract class MyApi {
public final boolean equals(Object other) {
if (other == this) {
return true;
}
if (other instanceof MyApi) {
return equals((MyApi)other);
}
return false;
}
protected abstract boolean equals(MyApi other);
}
or a more simple version:
public abstract class MyApi {
public boolean equals(Object other) {
throw new UnsupportedOperationException("equals() not overridden: " + getClass());
}
}
EDIT (gave it a try after the comment from @CodeConfident, thanks! Never assumed it would work):
You can also simply declare equals()
in an abstract class (not in an interface!) and therefore hide the Object
implementation and enforce a new implementation in any subclass:
public abstract class MyApi {
public abstract boolean equals(Object obj);
public abstract int hashCode();
}
Anyway you should always implement equals()
and hashCode()
together to fulfil the contract.