Object Cloning is one of the extraordinary features provided by Java programming, which helps in creating the same copy or duplicating an object of Java class. This entire duplication of an object is done by the clone() method. This method is used in a situation where programmers want to create the same to the same copy of an existing object, which eventually reduces the extra task of processing.
Let us now understand how this method can be implemented. The clone() method definition is within the Java Object class, and you have to override this method in order to use it. For using this predefined method, you have to use the java.lang.Cloneable interface and implement it with that specific class whose object cloning you want to make. If you do not implement this interface, your clone method will pop up with a CloneNotSupported Exception.
Example:
import java.util.ArrayList;
class Example1 {
int d, g;
}
//cloning
class Example2 implements Cloneable {
int k, s;
Example1 ex1 = new Example1();
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class CloneProgram {
public static void main(String argu[]) throws CloneNotSupportedException {
Example2 ex2 = new Example2();
ex2.k = 1;
ex2.s = 2;
ex2.ex1.d = 3;
ex2.ex1.g = 4;
Example2 ex22 = (Example2) ex2.clone();
ex22.k = 500;
ex22.ex1.d = 800;
System.out.println(ex2.k + " " + ex2.s + " " +
ex2.ex1.d + " " + ex2.ex1.g);
System.out.println(ex22.k + " " + ex22.s + " " +
ex22.ex1.d + " " + ex22.ex1.g);
}
}