...
Unfortunately, in this case it is impossible to extend the Card
class by class by adding a value or field in the subclass while preserving the Java equals()
contract contract. This problem is not specific to the Card class but applies to any class hierarchy that can consider equal instances of distinct subclasses of some superclass. For such cases, use composition rather than inheritance to achieve the desired effect effect [Bloch 2008], [Liskov 1994], [Cline C++ Super-FAQ]. It is fundamentally impossible to have a class that both allows arbitrary subclass extensions and permits an equals()
method that is reflexive, symmetric, and transitive, as is required by Object.equals()
. In the interests of consistency and security, we forgo arbitrary subclass extensions, and assume that {{Card.equals()}} may impose certain restrictions on its subclasses.
This compliant solution adopts this approach by adding a private card
field to the XCard
class class and providing a public viewCard()
method.
...
Violating the general contract when overriding the equals()
method can lead to unexpected results.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MET08-J | Low | Unlikely | Medium | P2 | L3 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
CodeSonar |
| FB.BAD_PRACTICE.EQ_GETCLASS_AND_CLASS_CONSTANT FB.CORRECTNESS.OVERRIDING_EQUALS_NOT_SYMMETRIC | equals method fails for subtypes equals method overrides equals in superclass and may not be symmetric | ||||||
SonarQube Java Plugin |
| S2162 |
...
Related Guidelines
Bibliography
...
[API 2014] | Class URI Class URL (method equals() ) |
Item 8, "Obey the General Contract When Overriding | |
\[Cline C++ Super-FAQ\] | |
Section 9.2, "Overriding the | |
Chapter 3, "Classes, Strings, and Arrays," section "The Object Class (Equality)" | |
\[Liskov 1994\] | |
[Sun 2006] | Determining If Two Keys Are Equal (JCA Reference Guide) |
"More Joy of Sets" |
...
...