Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Unfortunately, in this case it is impossible to extend the Card class by adding a value or field in the subclass while preserving the Java equals() 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 [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.

...

S2162
ToolVersionCheckerDescription
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V
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

JAVA.COMPARE.CTO.ASSYM
JAVA.IDEF.NOEQUALS
JAVA.IDEF.CTONOEQ
JAVA.IDEF.CTOEQ

Asymmetric compareTo (Java)
Missing Equals Override (Java)
compareTo without equals (Java)
compareTo/equals mismatch (Java)

Parasoft Jtest

Include Page
Parasoft_V
Parasoft_V

CERT.MET08.EQREFLMake sure implementation of Object.equals(Object) is reflexive
SonarQube
Include Page
SonarQube_V
SonarQube_V
S2162"equals" methods should be symmetric and work for subclassesSonarQube Java Plugin
Include Page
SonarQube Java Plugin_VSonarQube Java Plugin_V


Related Guidelines

MITRE CWE

CWE-697, Insufficient Comparison

...

[API 2014]Class URI
Class URL
(method equals())

[Bloch 2008]

Item 8, "Obey the General Contract When Overriding equals"

\[Cline, C++ Super-FAQ\]

[Darwin 2004]

Section 9.2, "Overriding the equals Method"

[Harold 1997]

Chapter 3, "Classes, Strings, and Arrays," section "The Object Class (Equality)"

\[Liskov 1994\]]

Liskov, B. H.Wing, J. M. (November 1994). A behavioral notion of subtypingACM Trans. Program. Lang. Syst.16 (6). pp. 1811–1841. doi:10.1145/197320.197383. An updated version appeared as CMU technical report: Liskov, BarbaraWing, Jeannette (July 1999). "Behavioral Subtyping Using Invariants and Constraints" (PS).

[Sun 2006]

Determining If Two Keys Are Equal (JCA Reference Guide)

[Techtalk 2007]

"More Joy of Sets"

...