【问题标题】:Equals method when dealing with inheritance and no instance variables处理继承和没有实例变量时的equals方法
【发布时间】: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方法?

【问题讨论】:

标签: java inheritance equals instance-variables


【解决方案1】:

如果您没有在StoreToys 中引入任何新字段,您可以使用instanceof 编写检查以验证otherObject 可以转换为Store

@Override
public boolean equals(Object otherObject) {
  if (this == otherObject) {
    return true;
  }
  if (!(otherObject instanceof Store)) {
    return false;
  }
  Store otherStore = (Store) otherObject;
  return area == otherStore.area; 
}

【讨论】:

  • 你需要一个! oninstanceof
猜你喜欢
  • 2013-05-16
  • 2012-12-03
  • 2013-08-16
  • 1970-01-01
  • 2012-11-05
  • 2014-10-28
  • 1970-01-01
  • 2012-06-09
  • 1970-01-01
相关资源
最近更新 更多