Cloning is the process of creating a copy of an object. To create a copy, you need to call the clone() method on the class that implements the Cloneable interface. 1. The importance of cloning 2. Types of cloning 3. The return type of the clone() method 4. Alternatives to cloning 5. Questions about cloning Although all classes inherit the clone() method from the Object class, for cloning it is also necessary to implement the Cloneable interface . If you try to call the clone() method without implementing the interface, you will receive a CloneNotSuppoted exception. Reloading the clone() method and implementing the Cloneable interface is all you need to do. The Cloneable interface is a token interface, just like the Serializable interface.
Importance of cloning
Here is an example code for calling clone() without the Cloneable interface implemented.package example.java; public class Test { public static void main(String[] args) { Test b1 = new Test(); try { Test b2 = (Test)b1.clone(); }catch (CloneNotSupportedException e) { e.printStackTrace(); } } }
conclusion:
Output: java.lang.CloneNotSupportedException: example.java.Test at java.lang.Object.clone(Native Method) at example.java.Test.main(Test.java:8)