Java Reference
In-Depth Information
First the clone method invokes super.clone . This invocation is very im-
portant because the superclass may be working around its own prob-
lem of shared objects. If you do not invoke the superclass's method,
you solve your own cloning problem but you may create another one.
Furthermore, super.clone will eventually invoke the method Object.clone ,
which creates an object of the correct type. If the IntegerStack imple-
mentation of clone used new to create an IntegerStack object, it would be
incorrect for any object that extended IntegerStack . The extended class's
invocation of super.clone would give it an IntegerStack object, not an ob-
ject of the correct, extended type. The return value of super.clone is then
cast to an IntegerStack reference.
Object.clone initializes each field in the new clone object by assigning it
the value from the same field of the object being cloned. You then need
only write special code to deal with fields for which copying the value is
incorrect. IntegerStack.clone doesn't need to copy the top field, because
it is already correct from the "copy values" default. It must, however,
make a copy of the buffer array, which is done by cloning the arrayall
arrays can be cloned, with clone returning a reference of the same type
as the array reference on which clone was invoked.
With the specialized clone method in place, the example code now cre-
ates memory that looks like this:
Cloning is an alternative form of construction but is not recognized as
construction by the system. This means that you have to be wary of us-
ing blank finals (see page 46 ) that can be set only in constructors. If the
value of the final field should be a copy of the value in the object being
cloned, then there is no problem since Object.clone will achieve this. If
copying the value is not appropriate for the field then it cannot be de-
clared final . In this example, the buffer array is immutable for the life
 
Search WWH ::




Custom Search