Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

How do you prevent for creating another instance of Singleton using clone() method in java?

user-image
Question added by Mohd shahnawaz khan , Associate Project , Cognizant Technology Solution
Date Posted: 2014/04/23

The class will need to implement the clone() mehod as below:

 

public class Singleton {

 

    private static final Singleton singleton = new Singleton();

    private Singleton() { }

    public static Singleton getInstance(){

        return singleton;

    }

    @Override

    protected Object clone() throws CloneNotSupportedException {

        throw new CloneNotSupportedException("Cloning of this class is not allowed"); 

    }

}

Maria Thomas
by Maria Thomas , Tech Lead , J P Morgan Chase

If your class which is based on the Singleton pattern does not implement the Cloneable interface then the clone() method cannot be called on that object. 

More Questions Like This