• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Java Clone

 
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What is the use of clone and when should we use it.
 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


clone is used for _shallow copying_


Everything's right except this. DEEP COPY is the right term.
 
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
YES. You're right. Everything you said is true. Details in Java API for Object.clone().
reply
    Bookmark Topic Watch Topic
  • New Topic