Hi Folks!
Does clone create a another singleton object ?
We all knows that Singleton means creating only one instance of the Class. But what happens when clone() method from objects class is applied on same class.
Does it hamper the whole purpose of singleton , if So, is there any other ways to create Singleton class as well as use Clone method ?
Answer: We can still create a copy of the Singleton object by cloning it using the Object’s clone() method. To forbid this, We need to override the Object’s clone method, which throws a CloneNotSupportedException exception:
public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
And thus we have achieved Singleton (only one instance of object) and Cloning also.
Happy Coding !!!