clone() method and Singleton pattern in Java

When we are writing a class using the Singleton pattern, there should be only one instance of that class at a time. We implement this by making the constructor private and adding a getInstance() method.

But what happens if we clone an instance of this class? You might think it won’t work because the constructor is private. But it works!! So we can actually make two instances of that class. Java does NOT handle this and we should do that by ourselves.

So how can we stop this? We need to override the clone() method like this,

@Override
protected Object clone() throws CloneNotSupportedException{
	throw new CloneNotSupportedException();
}

Now whenever we try to make a clone it will throw this CloneNotSupportedException.

One thought on “clone() method and Singleton pattern in Java

  1. I do not know if it’s justt me or iff everyone else experiencing issues with your blog.
    It looks like some oof the text on your content are running off
    the screen. Can someone else please comnent and
    let me know iif this is happening too them as well?

    This could be a issue with my browser becaus I’ve had this
    happen before. Kudos

Leave a comment