• 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

Is it possible to clone this object?

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

I have a program to illustrate Singleton pattern. My doubt is: "is it possible to create second object / instance of the following class / object using clonable porperty" ??

Please help me
 
Sheriff
Posts: 22781
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No it isn't. To be able to create a second instance using cloneable, your class must meet the following requirements:
1) it must implement Cloneable, either directly or through a super class.
2) it's clone() method cannot throw an exception to prevent it from returning a clone
3) it's clone() method must actually return a different instance.

I planned on adding that the clone() method should be public, but it doesn't need to. If it's still protected the number of classes that can clone() the object is decreased but it's not 0.

Note on 2):
if you extend a class that is cloneable you can throw an exception to disallow cloning:


Note on 3):
the Javadoc of Object.clone() specifies that for any object x, x.clone() == x is allowed. Therefore the following is a valid clone() implementation for singleton objects:
You should only do this if you extend a class that is cloneable, otherwise just don't make your own class cloneable. This way is actually nicer than throwing an exception since calling code doesn't get an exception they don't expect.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic