Understanding Cloneable interface in Java
What is Object Cloning?
Object Cloning is a process of generating the exact field-to-field copy of object with the different name. The cloned object has its own space in the memory where it copies the content of the original object. That’s why when we change the content of original object after cloning, the changes does not reflect in the clone object.
Can we clone any object in Java?
No, we can’t. When we try cloning an object instance directly that doesn’t implement a marker interface called ‘Cloneable’, it results in an exception called CloneNotSupportedException. Hence, to allow cloning an object instance, the respective object class must implement Cloneable interface. For example –
public class Employee { private String name; public Employee(String name) { this.name = name; } public String getName() { return name; } public static void main(String[] args) { Employee emp = new Employee("Abhi"); try { Employee emp2 = (Employee) emp.clone(); System.out.println(emp2.getName()); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } }
The above code when executed throws an exception as –
java.lang.CloneNotSupportedException: Employee at java.base/java.lang.Object.clone(Native Method) at Employee.main(Employee.java:16)
Note that Cloneable is a marker interface, which means it doesn’t has any clone method specification. In the above code snippet, implementing Cloneable just indicates to the JVM that an Employee class instance can be cloned and Object class’s clone method is legal for the Employee class to override.
Below is how you can correctly clone an Employee class instance as well as override the Object’s clone method in the Employee class.
public class Employee implements Cloneable { private String name; public Employee(String name) { this.name = name; } public String getName() { return name; } public Object clone()throws CloneNotSupportedException{ return (Employee)super.clone(); } public static void main(String[] args) { Employee emp = new Employee("Abhi"); try { Employee emp2 = (Employee) emp.clone(); System.out.println(emp2.getName()); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } }
Other marker interfaces are Serializable, Cloneable and Remote interface.
Published on Java Code Geeks with permission by Abhimanyu Prasad, partner at our JCG program. See the original article here: Understanding Cloneable interface in Java Opinions expressed by Java Code Geeks contributors are their own. |