Can anybody clear my confusion on the object cloning concept.
I wrote a singleton class ... then somebody told me with cloning I can get one more object. Then I started searching over the internet.
I read many articles saying to avoid cloning we need to override the Object clone() method.. but what is the need of it..
As per the documentation,
"Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown."
Calling the clone method on an object, will result in throwing an exception at run time.
Hence, when I am writing a singleton class and not implementing Cloneable interface, there is no chance of anyone cloning this singleton object. Even though clone method comes from Object super class..
I guess, any object whose class implements this Cloneable interface is eligible for cloning.. Please clear me if I am wrong..
Hence, when I am writing a singleton class and not implementing Cloneable interface, there is no chance of anyone cloning this singleton object. Even though it comes from Object super class..
There are some ways by which you can clone it, one of them being
Here are few links so that you can find more about singletons
Can anybody clear my confusion on the singleton object cloning concept.
I read many articles saying to avoid cloning we need to override the Object clone() method..
But as per the documentation,
"Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown."
Hence, when I am writing a singleton class and not implementing Cloneable interface, there is no chance of anyone cloning this singleton object. Even though it comes from Object super class..
I guess, any object whose class implements this Cloneable interface is eligible for cloning.. Please clear me if I am wrong..
Thanks
If you want to create a Singleton Class, which should not be cloned by any other Class, simply DO OVERRIDE clonable interface's clone() method with a blank implementation.[Edited the post after referring Sumit's post above]
Hope this clears your doubt, else please reframe the question.
Juni Panda
Greenhorn
Joined: Mar 18, 2012
Posts: 5
posted
0
But when I am writing a singleton class and not implementing Cloneable interface, there is no chance of anyone cloning this singleton object. right?
Then why to override the clone method?