Object cloning is a method of creating an exact copy of an object. To do this, use the clone() method of the object class to clone the object. CloneableThe interface must be implemented by the class whose object clone is to be created. If we do not implement the Cloneable interface, the clone() method will generate CloneNotSupportedException.
The clone() method saves the extra processing of creating an exact copy. Purpose. If we use the new keyword to execute, a lot of processing will need to be performed, so we can use object cloning. Syntaxprotected Object clone() throws CloneNotSupportedException
public class EmployeeTest implements Cloneable { int id; String name = ""; Employee(int id, String name) { this.id = id; this.name = name; } public Employee clone() throws CloneNotSupportedException { return (Employee)super.clone(); } public static void main(String[] args) { Employee emp = new Employee(115, "Raja"); System.out.println(emp.name); try { Employee emp1 = emp.clone(); System.out.println(emp1.name); } catch(CloneNotSupportedException cnse) { cnse.printStackTrace(); } } }
Raja Raja
The above is the detailed content of What is the use of object cloning in Java?. For more information, please follow other related articles on the PHP Chinese website!