【发布时间】:2018-09-30 08:07:42
【问题描述】:
这是我们在类中实现equals方法的方式。
以区域为实例变量的 A 类(商店):
@Override
public boolean equals(Object otherObject) {
if (this == otherObject) {
return true;
}
if (otherObject == null || getClass() != otherObject.getClass()) {
return false;
}
Store otherStore = (Store) otherObject;
return area == otherStore.area;
}
Class B (StoreToys) 扩展了 Class A (Store) 并且没有实例变量(处理继承)
我应该如何为这个类编写equals方法?
【问题讨论】:
-
getClass() != otherObject.getClass()你为什么要这样做而不是instanceof?getClass是 Effective Java 明确警告您不要做的事情,因为它违反了 Liskov 替换原则。
标签: java inheritance equals instance-variables