Make your class Non-Cloneable

 

 

                  Cloning is a way to obtain an object that is in the same state as the source.  To initialize an object using the clone() method the result should be an object with instance variable values identical to the values of the sources instance variable values.  This is a quick and easy way to duplicate objects without having to manually replicate the values of the classÕs variables.  This method can be very useful in a variety of applications. [23]

                  The problem with cloning is that a typical clone method will produce a shallow clone, one that simply has references to the variables in the original object.  This is a problem from a design standpoint because changes in one object will affect the values of the other.  Even if the clone method is set up to create a deep clone by cloning all the internal variables and using those to create the new object there is a problem.  This is a way to create a new object of a class without calling one of its constructors.  This sidesteps any security measures that you have built into the original constructors.  Any class invariants that you may have set up or any restrictions on the number of objects of a certain class are completely irrelevant.  There is now an object that was created without using any of the constructors. [23]

                  This problem is solved with a method very similar to the way the serialization problem was solved.  Since it is possible to extend your class and add previously unimplemented interfaces it is possible that a clone method could be defined even if you donÕt do it yourself.  To prevent this possibility from happening the clone interface must be implemented and the clone() method must explicitly throw an exception. [2]  The following code will do such a thing:

 

Public void final clone() throws java.lang.CloneNotSupportedException {

         throw new java.lang.CloneNotSupportedException();

 }