JAVA - Object Cloning
Is the way of creating the same copy of object without calling the class constructor. It means we can make any class object multiple times without calling its default constructor. Wherever we required the same object then we can go with cloneable classes as loading of the object is pretty much faster as compared to creating new objects multiple times.
Internally it uses clone() method, which is one of the ways of the object class.
We can achieve cloning by implementing any class with the Cloneable interface.
For more understanding please refer below code.
public class EmployeeCloneable implements Cloneable{
private String name;
private String add;
public EmployeeCloneable(String name, String add){ //Only one time constructor cal
this.name = name;
this.add = add;
System.out.println("I am constructor");
}
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAdd() {
return add;
}
public void setAdd(String add) {
this.add = add;
}
public static void main(String[] args) throws CloneNotSupportedException {
EmployeeCloneable emp = new EmployeeCloneable("Test", "1");
//try to use comment line then you will be see two time constrictor call happens
EmployeeCloneable emp1 = (EmployeeCloneable)emp.clone();//new EmployeeCloneable("Test ", "1");
System.out.println(emp);
System.out.println(emp1);
}
@Override
public String toString() {
return "EmployeeCloneable [name=" + name + ", add=" + add + "]";
}
}
Output:
I am constructor
EmployeeCloneable [name=Test, add=1]
EmployeeCloneable [name=Test, add=1]
Please add on comments and like this lesson, if it gave you some revision or refreshment on “JAVA - Object Cloning” concepts.