The programming language Java was introduced to the IT community as
an “easy-to-learn” and “easy-to-use” language (typically referring to C++
for comparison). While this is certainly true, it turns out that even this
supposedly easy language offers a lot of choices and comes with many programming
idioms that must be understood thoroughly in order to produce high-quality
software implemented in Java.
In this tutorial we focus on the implications of reference semantics
on object copying and comparison. By default Java uses reference
semantics; value semantics are optional and can be provided for each new
class in form of implementations of clone(), equals(), and hashCode().
These functions are particularly important in case of superclasses, since
no correct implementation of a subclass can be provided if the superclass
already lacks support for value semantics.
Correct and symmetric implementation of clone(), equals(), and hashCode()
is a non-trivial task. Questionable implementations of these functions
can be found galore (in the JDK, in popular textbooks, even in commercial
applications). In this tutorial we go into the details of correct and complete
implementations. |