• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java Clone

 
aakash bhatt
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the use of clone and when should we use it.
 
Gaurav Mac Mathur
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 _
Cheers
 
Pavel Halas
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

clone is used for _shallow copying_

Everything's right except this. DEEP COPY is the right term.
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Pavel Halas
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
YES. You're right. Everything you said is true. Details in Java API for Object.clone().
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic