Composition or inheritance may be used to create a new class that both encapsulates an existing class and adds one or more fields. When one class extends another in this way, the concept of equality for the subclass may or may not involve its new fields. That is, when comparing two subclass objects for equality, sometimes their respective fields must also be equal, and other times they need not be equal. Depending on the concept of equality for the subclass, the subclass might override equals()
. Furthermore, this method must follow the general contract for equals()
, as specified by the Java Language Specification [JLS 20052015].
An object is characterized both by its identity (location in memory) and by its state (actual data). The ==
operator compares only the identities of two objects (to check whether the references refer to the same object); the equals()
method defined in java.lang.Object
can be overridden to compare the state as well. When a class defines an equals()
method, it implies that the method compares state. When the class lacks a customized equals()
method (either locally declared or inherited from a parent class), it uses the default Object.equals()
implementation inherited from Object
. The default Object.equals()
implementation compares only the references and may produce unexpected results.
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MET08-J | Low | Unlikely | Medium | P2 | L3 |
Related Guidelines
Bibliography
[API 2006] | |
Item 8. , "Obey the general contract when overriding equalsGeneral Contract When Overriding | |
Section 9.2, "Overriding the | |
Chapter 3, "Classes, Strings, and Arrays," section "The Object Class (Equality)" | |
[Sun 2006] | Determining If Two Keys Are Equal (JCA Reference Guide) |
"More Joy of Sets" |
...