继承且无实例变量场景下的equals方法实现方案咨询
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
StoreToysobjects: ThegetClass()check passes, and the parent method correctly validates theirareavalues. - When comparing a
StoreToysand aStoreobject: ThegetClass()check fails, returningfalse—which aligns with theequals()contract's symmetry requirement (ifa.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

