• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to avoid a singleton with a cloneable super class from being cloned?

 
Faisal syed
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Friends,
Please help me on this.

 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would say it's bad design to create a singleton that extends a Cloneable class in the first place.

But if you're going to do it, the way to prevent cloning would be to throw CloneNotSupportedException.
 
Rob Spoor
Sheriff
Pie
Posts: 20494
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not really. That is a checked exception, and the super class usually drops the exception from its own clone() implementation. (It doesn't in this example, but why make a class implement Cloneable without overriding clone()?)

UnsupportedOperationException is available, although it isn't documented to be thrown from clone(). Overriding clone() in the singleton and returning this is perfectly legal though; the Javadoc for clone() says this is unusual but not forbidden.
 
Faisal syed
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jeff/Rob,
Thanks for the help. I have another query.
When I only need a shallow copy of the object, it is fair enough to use the clone functionality
provided by java.lang.Object, and not override the clone() method myself. Is this correct?

Thanks
Faisal
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Faisal syed wrote:Hi Jeff/Rob,
Thanks for the help.


Rob's advice is more on the money than mine. I was being lazy and went for the easy out.

If your class's clients know they're using your class (as opposed to using it via a reference to the superclass) and if the semantics say that it's supposed to be a singleton, then I think throwing UnsupportedOperationException is the way to go, and make sure that you document that it does this.

On the other hand, if you don't want client code to have to know or care that it's the subclass, or that it's a non-cloneable singleton, then just returning this seems appropriate.

However, to reiterate what I said previously, why would you derive a singleton from a Cloneable class in the first place?

When I only need a shallow copy of the object, it is fair enough to use the clone functionality
provided by java.lang.Object, and not override the clone() method myself. Is this correct?


Yes, except that clone() is protected in Object, so you'll still have to override clone() to make it public, if your class descends directly from Object, or if none of the classes between yours and Object make it public.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic