Cloneable Interface in Java
The Java.lang.Cloneable interface is a marker interface. It was introduced in JDK 1.0. There is a method clone() in the Object class. Cloneable interface is implemented by a class to make Object.clone() method valid thereby making field-for-field copy. This interface allows the implementing class to have its objects to be cloned instead of using a new operator.
public interface Cloneable
Example 1: Below program explains that If you will try to Clone an object which doesn’t implement the Cloneable interface, it will CloneNotSupportedException, which you may want to handle.
prog.java:28: error: incompatible types: Object cannot be converted to Student Student s2 = s1.clone(); ^ 1 error
Example 2: Below code explains the proper usage of the Cloneable interface to make the Object.clone() method legal. Classes that implement this interface should override the Object.clone() method (which is protected) so that it can be invoked.
Deep Copy using clone() method
Deep Object Cloning is like creating an exact copy of the original object by copying the fields from the original object to the cloned object. A separate memory is allocated for the cloned objects where the original object content is copied. clone() method can create both shallow and deep copy of the original object based on the implementation of it. Deep copy creates a new memory with the contents same as the original object. That’s why when we change the content of the original object after cloning, the changes do not reflect in the clone object. There are types of copies such as Deep, Shallow, and Lazy Copy. The below code explains the deep copy using the clone() method.
10 20 30 40 100 20 300 0
Note: This interface does not contain the clone method. Therefore, it is not possible to clone an object merely by virtue of the fact that it implements this interface. Even if the clone method is invoked reflectively, there is no guarantee that it will succeed.