This is for Java . Hi Sir , In one of the interview somebody asked me , Can we stop cloning of Singleton class . | Core Java Forum
D
Deepak Kumar Tiwari Posted on 26/10/2020

Can we stop cloning of Singleton class .


Y
Yogesh Chawla Replied on 26/10/2020

Hi Deepak,

Yes we can stop cloning of Singleton Class Object. Singleton Class Object means only one instance in the entire application so we should stop the cloning of Singleton Class Object otherwise the relevance of Singleton concept will go away.

Check this code to stop cloning of Singleton Class Object. Here we are just raising the exception if as part of any other class, other programmer tries to create the instance of Singleton Class object. This is how we can enforce that Singleton Class object should not be cloned and one gets the exception.

package Java.src.com.programming.class1;

public final class SingeltonCloneTest implements Cloneable {

	    private static SingeltonCloneTest instance = null;

	    private SingeltonCloneTest() {
	     System.out.println("Singleton Object Instance");
	    }

	    public static SingeltonCloneTest getInstance() {

	        if (instance == null) {
	            instance = new SingeltonCloneTest();
	            return instance;
	        }
	        return instance;
	    }

	    @Override
	    protected Object clone() throws CloneNotSupportedException {

	        /*
	         * If clone is called on this class object
	         */
	        throw new CloneNotSupportedException();
	        // return super.clone();
	    }

	    public static void main(String[] args) {
	        SingeltonCloneTest test1 = SingeltonCloneTest.getInstance();
	        try {
	            SingeltonCloneTest test2 = (SingeltonCloneTest) test1.clone();
	        } catch (CloneNotSupportedException e) {
	            e.printStackTrace();
	        }
	    }

}

You can post all kinds of interview questions in this forum where you think you get stuck or where you think you were not quite confident while answering it.