• Post Reply Bookmark Topic Watch Topic
  • New Topic

Is it possible to clone this object?  RSS feed

 
Anu satya
Ranch Hand
Posts: 146
  • Mark post as helpful
  • send pies
  • 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
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!