Java Reference
In-Depth Information
Cloning Objects
Java does not provide an automatic mechanism to clone (make a copy) an object. Recall that when you assign a
reference variable to another reference variable, only the reference of the object is copied, not the content of the
object. Cloning an object means copying the content of the object bit by bit. If you want objects of your class to be
cloned, you must reimplement the clone() method in your class. Once you reimplement the clone() method, you
should be able to clone objects of your class by calling the clone() method. The declaration of the clone() method in
the Object class is as follows:
protected Object clone() throws CloneNotSupportedException
You need to observe few things about the declaration of the clone() method.
protected . Therefore, you will not be able to call it from the client code. The
following code is not valid:
It is declared
Object obj = new Object();
Object clone = obj.clone(); // Error. Cannot access protected clone() method
This means you need to declare the clone() method public in your class if you want the client
code to clone objects of your class.
Object . It means you will need to cast the returned value of the clone()
method. Suppose MyClass is cloneable. Your cloning code will look as
Its return type is
MyClass mc = new MyClass();
MyClass clone = (MyClass)mc.clone(); // Need to use a cast
You do not need to know any internal details about an object to clone it. The clone() method in the Object class
has all the code that is needed to clone an object. All you need is to call it from the clone() method of your class. It
will make a bitwise copy of the original object and return the reference of the copy.
The clone() method in the Object class throws a CloneNotSupportedException . It means when you call the
clone() method of the Object class, you need to place the call in a try-catch block, or rethrow the exception. You will
learn more about the try-catch block in Chapter 9. You have the option not to throw a CloneNotSupportedException
from the clone() method of your class. The following snippet of code is placed inside the clone() method of your
class, which calls the clone() method of the Object class using the super keyword:
YourClass obj = null;
try {
// Call clone() method of the Object class using super.clone()
obj = (YourClass)super.clone();
}
catch (CloneNotSupportedException e) {
e. printStackTrace();
}
return obj;
 
Search WWH ::




Custom Search