Wiki Markup |
---|
Composition or inheritenceinheritance may be used to create a new class that both encapsulates an existing class and adds one or more fields. When a subclass 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 2005|AA. Bibliography#JLS 05]\]. |
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 customized by overriding 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 that is inherited from Object
which . The default Object.equals()
implementation compares only the references and may produce unexpected results.
...