强制“等于”在界面中 [英] Enforce "equals" in an interface
问题描述
我有一个接口,我希望实现此接口的每个人都实现一个覆盖的equals方法。
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?
我猜这种情况的方式是实现我的接口的类将自动从Object获取equals,从而使接口满意。
The way I guess this will happen is that the class that implements my interface will automatically get the equals from Object therefore making the interface happy.
推荐答案
不,你只能创建一个抽象类而不是像这样的接口:
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);
}
或更简单的版本:
public abstract class MyApi {
public boolean equals(Object other) {
throw new UnsupportedOperationException("equals() not overridden: " + getClass());
}
}
编辑(在@CodeConfident发表评论后试一试,谢谢!从未认为它会起作用):
EDIT (gave it a try after the comment from @CodeConfident, thanks! Never assumed it would work):
您也可以简单地声明等于( )
在抽象类中(不在接口中!)因此隐藏 Object
实现并在任何子类中强制执行新实现:
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();
}
无论如何,你应该总是实现等于()
和 hashCode()
一起履行合同。
Anyway you should always implement equals()
and hashCode()
together to fulfil the contract.
这篇关于强制“等于”在界面中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!