Java Reference
In-Depth Information
DoubleHolder dh = new DoubleHolder(100.00);
DoubleHolder dhClone = (DoubleHolder) dh.clone();
At this point, there are two separate objects of the
DoubleHolder
class. The
dh
variable references the original
object and
dhClone
variable references the cone of the original object. The original as well as the cloned object hold
the same value of
100.00
. However, they have separate copies of the value. If you change the value in the original
object, for example,
dh.setValue(200)
, the value in the cloned object remains unchanged. Listing 7-8 shows how
to use the
clone()
method to clone an object of the
DoubleHolder
class. The output proves that once you clone an
object, there are two separate objects in memory.
Listing 7-8.
A Test Class to Demonstrate Object Cloning
// CloningTest.java
package com.jdojo.object;
public class CloningTest {
public static void main(String[] args) {
DoubleHolder dh = new DoubleHolder(100.00);
// Clone dh
DoubleHolder dhClone = (DoubleHolder)dh.clone();
// Print the values in original and clone
System.out.println("Original:" + dh.getValue());
System.out.println("Clone :" + dhClone.getValue());
// Change the value in original and clone
dh.setValue(200.00);
dhClone.setValue(400.00);
// Print the values in original and clone again
System.out.println("Original:" + dh.getValue());
System.out.println("Clone :" + dhClone.getValue());
}
}
Original:100.0
Clone :100.0
Original:200.0
Clone :400.0
From Java 5, you need not specify the return type of the
clone()
method in your class as the
Object
type. You
can specify your class as the return type in the
clone()
method declaration. This will not force the client code to
use a cast when it call the
clone()
method of your class. The following snippet of code shows the changed code for
the
DoubleHolder
class, which will compile only in Java 5 or later. It declares
DoubleHolder
as the return type of the
clone()
method and uses a cast in the
return
statement.