jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes cloning question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "cloning question" Watch "cloning question" New topic

cloning question

Edwin Davidson

Joined: Nov 26, 2003
Posts: 27
On page 225 of Peter van der Linden's Just Java 2 (5th edition) exercise 5 is written as this:

"write some code to clone an object of your class. Change your version of
clone() to do a deep copy for your class. Run the clone program again,
and make it print out enough details that you can tell the difference
between a shallow and a deep clone."

The exercise before it (exercise 4) says to override Object.clone() to do
a shallow copy for your class. My code for exercise 4 is here:
class testclass implements Cloneable {

public Object clone() throws CloneNotSupportedException {
System.out.println("clone "+ ++count);
return super.clone();

int geti() {
return i;

int i;
double d;
static int count;

testclass() {
System.out.println("constructor "+ ++count);

class exercise4 {
public static void main(String args[]) throws
CloneNotSupportedException {
testclass tc1=new testclass();
testclass tc2;
tc2=(testclass) tc1.clone();
System.out.println("tc1 d "+tc1.d);
System.out.println("tc1 i "+tc1.i);
System.out.println("clone d "+tc2.d);
System.out.println("running clone geti() "+tc2.geti());
How do I do a deep clone ? The code can't be that much different. I know
if I see the code for it I'll know how it works straight off.

Thanks to all.
Nigel Browne
Ranch Hand

Joined: May 15, 2001
Posts: 673
This whitepaper will help you understand the difference between shallow and deep cloning.
marc weber

Joined: Aug 31, 2004
Posts: 11343

In a nutshell, cloning provides only a shallow copy because the member references still point to the same objects as in the original copy. For a deep copy, you would need to also clone any member objects as well (and any member objects of those objects, and so on...).

See Appendix A to Bruce Eckel's Thinking in Java...


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
I agree. Here's the link: http://aspose.com/file-tools
subject: cloning question
It's not a secret anymore!