Interview Questions

Disallowing Cloning

Java Interview Questions for Cloning and Cloneable


(Continued from previous question...)

Disallowing Cloning

Java's cloning mechanism enables you to allow cloning, allow cloning conditionally, or forbid cloning altogether. If you wish to completely forbid cloning, you have a few different approaches to choose from. To decide which way to forbid cloning upon a particular class of objects, you must know something about the class's superclasses.

If none of the superclasses implement Cloneable or override Object's clone() method, you can prevent cloning of objects of that class quite easily. Simply don't implement the Cloneable interface and don't override the clone() method in that class. The class will inherit Object's clone() implementation, which will throw CloneNotSupportedException anytime clone() is invoked on objects of that class. All the classes shown as examples in this book prior to the CoffeeCup class declared immediately above used this method of preventing cloning. By doing nothing, they disallowed cloning. Thus, forbidding cloning is the default behavior for an object.

In cases where a superclass already implements Cloneable, and you don't want the subclass to be cloned, you'll have to override clone() in the subclass and throw a CloneNotSupportedException yourself. In this case, instances of the superclass will be clonable, but instances of the subclass will not.

(Continued on next question...)

Other Interview Questions