Java Reference
In-Depth Information
A First Look at the clone Method
Every object inherits a method named clone from the class Object . The method
clone has no parameters and is supposed to return a copy of the calling object.
However, the inherited version of clone was not designed to be used as is. Instead,
you are expected to override the definition of clone with a version appropriate for the
class you are defining. The officially sanctioned way to define the method clone turns
out to be a bit complicated and requires material we do not cover until Chapter 13, so
we will describe how to do so in that chapter. In this section, we will describe a simple
way to define clone that will work in most situations and will allow us to discuss
how polymorphism interacts with the clone method. If you are in a hurry to see the
officially sanctioned way to define clone , you can read Chapter 13 immediately after
this section (Section 8.1) with no loss of continuity in your reading.
The method clone has no parameters and should return a copy of the calling
object. The returned object should have identical data to that of the calling object, but
it normally should be a different object (an identical twin or “a clone”). You usually
want the clone method to return the same kind of copy as what we have been defining
for copy constructors, which is what is known as a deep copy . (You many want to review
the subsection entitled “Copy Constructors” in Chapter 5.)
A clone method serves very much the same purpose as a copy constructor but, as
you will see in the Pitfall titled “Limitations of Copy Constructors” there are situations
where a clone method works as you want, whereas a copy constructor does not
perform as desired.
As with other methods inherited from the class Object , the method clone needs
to be redefined (overridden) before it performs properly. The heading for the method
clone in the class Object is as follows:
clone
protected Object clone()
If a class has a copy constructor, you can define the clone method for that class
by using the copy constructor to create the copy returned by the clone method. For
example, consider the class Sale defined in Display 8.1. The following definition of
the clone method can be added to the definition of Sale given in Display 8.1 :
public Sale clone()
{
return new Sale( this );
}
Using a copy constructor is not the officially sanctioned way to define a clone method,
and in fact, the Java documentation says you should not define it this way. However,
it does work correctly, and some authorities say it is acceptable. In Chapter 13, we
will discuss the official way of defining the method clone when we introduce the
Cloneable interface.
Note that, as we defined the method clone for the class Sale , the method clone has
Sale as its return type and is given public rather than protected access. Despite these
 
Search WWH ::




Custom Search