- Clone (Java method)
clone()
is a method in the Java programming language for object duplication.Since objects in Java are manipulated through reference variables, there is no direct way to "copy" an object. (We would be trying to duplicate the reference variable rather than the object control referred to through that variable).Overview
Classes that want copying functionality must implement some method to do so. To a certain extent that function is provided by "
clone()
".clone()
acts like a constructor. Typically it calls theclone()
method of its superclass to obtain the copy, etc. until it eventually reachesObject
'sclone()
method. The special Javadoc:SE|name=clone()|java/lang|Object|clone() method in the base classObject
provides a standard mechanism for duplicating objects.The class Javadoc:SE|java/lang|Object's
clone()
method creates and returns a copy of the object, with the same class and with all the fields having the same values. However,clone()
throws a Javadoc:SE|java/lang|CloneNotSupportedException unless the class you are trying to use it on implements the marker interface Javadoc:SE|java/lang|Cloneable.The default implementation of
Object.clone()
performs ashallow copy . When a class desires adeep copy or some other custom behavior, they must perform that in their ownclone()
method after they obtain the copy from the superclass.The syntax for calling
clone
in Java is:or commonlywhich provides thetypecast ing needed to assign the genericObject
reference returned fromclone
to a reference to aMyClass
object.One disadvantage with the design of the
clone()
method is that the return type ofclone()
isObject
, and needs to be explicitly cast back into the appropriate type (technically a customclone()
method could return another type of object; but that is generally inadvisable).Another disadvantage is that one often cannot access the
clone()
method on an abstract type. Most interfaces and abstract classes in Java do not specify a publicclone()
method. As a result, often the only way to use theclone()
method is if you know the actual class of an object; which is contrary to the abstraction principle of using the most generic type possible. For example, if one has aList
reference in Java, one cannot invokeclone()
on that reference becauseList
specifies no publicclone()
method. Actual implementations ofList
likeArrayList
andLinkedList
all generally haveclone()
methods themselves, but it is inconvenient and bad abstraction to carry around the actual class type of an object.Alternatives
Increasingly,
clone()
is considered to be obsolete. [ [http://www.javapractices.com/topic/TopicAction.do?Id=71 Java Practices] ] However, there are alternatives, notably the use of acopy constructor - a constructor that accepts as a parameter another instance of the same class - or a factory method.clone()
and the Singleton patternWhen writing a class using the
Singleton pattern , only 1 instance of that class can exist at a time. As a result, the class must not be allowed to make a clone. To prevent this, override theclone()
method using the following code:(Note: This is only necessary if a superclass implements a publicclone()
method, or to prevent a subclass from using this class'sclone()
method to obtain a copy. Since classes don't usually inherit a publicclone()
method (Object
doesn't have a publicclone()
method), it is usually unnecessary to explicitly implement a non-functionalclone()
method.clone()
and class hierarchyWhen working with the clone() in a hierarchy of classes, there are several things that must be handled properly.
1) Every type reference that needs to call the clone function must have a clone() method in its own class or a publicly accessible clone() method in its parent classes. That means that if you want to clone a reference to an abstract base class, either the base class must have a clone() method, or one of its parents must have a publicly accessible clone() method.
Example - since varY1 is of type Y, then Y must have clone(), or a parent of Y must have clone()
2) Every class that has any data other than primitives that has to be cloned must contain a clone() function that handles it.This includes all objects and all primitives that are allocated with the 'new' command such as variable length arrays.(This assumes that the programmer wants the objects to be cloned (deep copy) and not just have their reference copied (shallow copy).)
Example - since class Z has a reference to an object of another class, there needs to be specific code to clone that object.
Easy Solution
The easiest solution to this is to make the base class "implements Cloneable" and have the base class and all sub-classes contain the clone() method.When a class has data in it that must be cloned, adding a line or two to the clone() method is straight forward.
Example
Downsides
If every class in your hierarchy has a clone() method, then when the actual class is cloned all of these functions will be called, adding some overhead. Over many calls this could be significant.
With complex object graphs deep copying can become problematic, with recursive references. Once one objects is cloneable, others tend to follow until the entire graph attempts to implements Cloneable. Sooner or later you run into an class that you can't make Cloneable.
It is not always appropriate to have multiple copies of the same object floating around. Besides, using clone() tends to defeat the "single object, multiple references" paradigm.
clone()
andfinal
fieldsGenerally,
clone()
is incompatible withfinal
fields. Because Javadoc:SE|name=clone()|java/lang|Object|clone() is essentially a default constructor (one that has no arguments) it is impossible to assign afinal
field within aclone()
method; a compiler error is the result. Where the value of the field is an immutable object this is okay; just let the 'constructor' copy the reference and both the original and its clone will share the same object.But where the value is a mutable object it must be deep copied. The only solution is to remove the
final
modifier from the field, giving up all the benefits it conferred.For this reason, many programmers prefer to make the objects in the hierarchy Serializable, and create copies by serializing the old object and then creating a new object from the resulting
bitstream , which should be nearly as fast as the calls to clone(), uses only one object's worth of extra memory, and that only during the operation, and handles final data members correctly.References
Wikimedia Foundation. 2010.