Wiki Markup |
---|
Composition may be used to create a new class that both encapsulates an existing class and also adds a valuevariable or field, the value of which must be equal for objects of this new class to be equal. When objects of this new class are equated with objects of the encapsulated class, the new class must override the {{Object.equals()}} method;. furthermoreFurthermore, 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 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 compares only the references and may produce counter-intuitive unexpected results.
The equals()
method applies only to objects, not primitives. It is unnecessary to override the equals
method when checking for logical equality is not useful. For example, enumerated types have a fixed set of distinct values that may be compared using ==
rather than the equals()
method. Note that enumerated types provide an equals()
implementation that uses ==
internally; this default cannot be overridden. More generally, subclasses that both inherit an implementation of equals()
from a superclass and also lack a requirement for additional functionality need not override the equals()
method.
...