• 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
  • Liutauras Vilda
  • Paul Clapham
Sheriffs:
  • paul wheaton
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Piet Souris
Bartenders:
  • Mike London

How to Clone an Object??

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Folks,

Can any one tell me How to clone an Object of a class?.I have tried to clone an object of a class using clone() method in Object class and it's throwing clone not supported exception.One more thing the clone method returns an object which is a protected object.How will I use that in a different class??.
Any sample codes would be appriciatable.
Thanks in Advance,
Murali
 
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You need your class to implement the Cloneable interface. Then you need to overwrite the clone method, from the Object class.
Hope this helps.
 
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your class needs to implement the Cloneable interface. Cloneable is simply a marker interface -- i.e. it does not have any methods.
Also the clone() method in Object class is protected. So if you want the clone() method for your class to be publicly accessible from anywhere, you can override this method to be public. However be sure to call super.clone() from your overriden clone() method in order to create the correct Object type.
For eg:

However remember that the Object clone() method creates a shallow copy, i.e. if your class has any object references, only the object references are cloned, not the objects themselves.
[ May 14, 2002: Message edited by: Junaid Bhatra ]
 
Murali Obla
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank u very much for ur help Mr.Ibrahim and Mr.Junaid.

Oops,I forgot about the method overridding. it's working now...
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic