强制一个类覆盖 .equals 方法 [英] Force a class to override the .equals method

查看:22
本文介绍了强制一个类覆盖 .equals 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆实现一个通用接口的类:命令.

I have a bunch of class who implement a common interface : Command.

这群类去映射.

为了让 Map 正常工作,我需要每个实现 Command 的类覆盖 Object.equals(Object other) 方法.

To get the Map working correctly, I need to each class who implements Command to override the Object.equals(Object other) method.

没关系.

但我想强制覆盖平等.=> 当实现命令的东西不覆盖等于时出现编译错误.

But i whould like to force the overriding of equals. => Have a compilation error when something who implement command dont override equals.

有可能吗?

顺便说一句,我还需要强制覆盖哈希码...

Edit : BTW , i will also need to forcing the override of hashcode...

推荐答案

不,你不能.但是,您可以做的是使用抽象基类而不是接口,并使 equals() 抽象:

No, you can't. What you can do, however, is use an abstract base class instead of an interface, and make equals() abstract:

abstract class Command {
   // put other methods from Command interface here

   public abstract boolean equals(Object other);
   public abstract int hashCode();
}

Command 的子类必须然后提供它们自己的 equals 和 hashCode 方法.

Subclasses of Command must then provide their own equals and hashCode methods.

强制 API 用户扩展基类通常是不好的做法,但在这种情况下可能是合理的.此外,如果您使 Command 成为抽象基类而不是接口,而不是在 addition 到 Command 接口中引入人工基类,那么您的 API 就没有风险用户弄错了.

It's generally bad practice to force API users to extend a base class but it may be justified in this case. Also, if you make Command an abstract base class instead of an interface, rather than introducing an artificial base class in addition to the Command interface, then there's no risk of your API users getting it wrong.

这篇关于强制一个类覆盖 .equals 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆