File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Java Clone Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Java Clone" Watch "Java Clone" New topic

Java Clone

aakash bhatt
Ranch Hand

Joined: Jan 09, 2003
Posts: 182
What is the use of clone and when should we use it.
Gaurav Mac Mathur
Ranch Hand

Joined: Feb 19, 2002
Posts: 47
When ever you have your own Business objects your objects must implement equals, clone and toString, this will greately help you in development also.
clone is used for _shallow copying_
Take for example your Object (a) has a refrence to some other object (b).

Now if you edit a.b the value of a1.b will also be changed...
but if you write a proper Clone Method copying Value By Value, you can fix this...
_Guru's correct me if i am wrong _
Pavel Halas
Ranch Hand

Joined: Jul 05, 2003
Posts: 35

clone is used for _shallow copying_

Everything's right except this. DEEP COPY is the right term.
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Originally posted by Pavel Halas:

Everything's right except this. DEEP COPY is the right term.

I think we all need to get on the same page here. I assume we are discussing Object.clone() and the Cloneable interface. Object.clone() returns a shallow copy. It just copies every field in the object to the cloned copy. If all the references are immutable then you will in fact have a deep copy or if the class' state consists of immutabales and/or primitives only. Also note that Object itself is not Cloneable. When you make a class Cloneable, chances are you will want to override the clone() method in Object and provide one that will create a deep copy of the object.

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Pavel Halas
Ranch Hand

Joined: Jul 05, 2003
Posts: 35
YES. You're right. Everything you said is true. Details in Java API for Object.clone().
I agree. Here's the link:
subject: Java Clone
Similar Threads
How do I add a object (copy) to a que or hashmap, and not a reference?
Doubt regarding clone method
clone() method
why clone method is provided in object class and not in clonable interface
WA #1.....word association