• Post Reply Bookmark Topic Watch Topic
  • New Topic

about clone  RSS feed

 
venkataramana raju
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hai,
can give me some real time examples of clone.
i mean where exatly we use clone in realy time?
thanks & regards
raja
 
Scott Selikoff
author
Bartender
Posts: 4093
21
Eclipse IDE Flex Google Web Toolkit
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Backing up data is one case, for example if you want to support an undo feature. You might also use clone if you anticipate making large changes to data and do not want these changes to persist. Finally, you can use clone if you are creating a new object where you want it to have some of the properties of some other object, but its own private data.
 
Greg Charles
Sheriff
Posts: 3015
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
... or if you have a mutable object that you are passing as a parameter or returning as a return value, and you don't want anyone else changing its values behind your back. Keep in mind though that the default behavior of clone() just returns a new reference to the same object. You will have to override this behavior to actually copy the object (and clone the member data as appropriate).
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Greg]: Keep in mind though that the default behavior of clone() just returns a new reference to the same object.

Ah, no, clone() is required to (and does) return a new object. I believe you're thinking of the fact that any fields in the object, if they're reference type, will still refer to the same objects the original fields referred to.

This shows that w2 is a separate instance of Wallace from w1 - but g1 and g2 both refer to the same Gromit instance. Wallace is cloned, but Gromit is not.
 
Greg Charles
Sheriff
Posts: 3015
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh, shoot. Jim is right. The default clone() behavior will make a copy of your object, but not a "deep" copy. If your class just contains primitives and immutables, that will be fine. Otherwise, you may need to override clone() to also make copies of your mutable member data.
 
venkataramana raju
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Thanks for your information,

i too got one idea after thinking some time
we can use clone for "drag and drop" while swing/awt(GUI) projects.

Am i right?
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!