Java : Singleton and Clone

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 !!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s