You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

继承且无实例变量场景下的equals方法实现方案咨询

How to Implement equals() for the StoreToys Subclass

Great question! Since StoreToys inherits from Store and has no additional instance variables, you have two solid, contract-compliant options for its equals() implementation—both leaning on the parent class's existing logic effectively.

Option 1: Don't Override equals() at All

This is the simplest and most recommended approach. The parent Store class's equals() already includes a critical type check:

if (otherObject == null || getClass() != otherObject.getClass()) { return false; }

This ensures only objects of the exact same class proceed to attribute comparison. Since StoreToys adds no unique state, comparing just the area field (handled by the parent method) is fully sufficient to determine equality between two StoreToys instances.

  • When comparing two StoreToys objects: The getClass() check passes, and the parent method correctly validates their area values.
  • When comparing a StoreToys and a Store object: The getClass() check fails, returning false—which aligns with the equals() contract's symmetry requirement (if a.equals(b) is true, b.equals(a) must also be true).

Option 2: Explicitly Override equals() (For Code Clarity)

If your team's style guide prefers explicit overrides even when inheriting functionality, you can simply delegate to the parent class's implementation:

@Override
public boolean equals(Object otherObject) {
    // Delegate all equality checks to the parent Store class
    return super.equals(otherObject);
}

This behaves exactly the same as not overriding the method, but makes it explicit to other developers that you've intentionally considered StoreToys' equality logic.

Critical Warning

Never modify the parent's core logic here (like removing the getClass() check or adding new comparisons). Since StoreToys has no unique state, altering the parent's implementation would break the equals() contract—for example, violating transitivity or symmetry.

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:07:32