What is object cloning ?
Answer : Any class that wants copy functionality should implement Cloneable interface and method “Object.clone()” available in Object class .
When call object class clone() method it acts like a copy constructor functionality. What it does is calls the superclass method to obtain copy until it finally reaches Object class clone() method and it provides mechanism to create duplicate objects.
As said any class want to copy it should implement marker interface Cloneable otherwise Object.clone() throws a CloneNotSupportedException.
If we use its default functionality it does shallow copy mean will give you reference of the object. When our need is to get deep copy of the object we should implement our own custom clone() functionality.
Below is the syntax for calling clone:
Object copy = object.clone();
OR we do casting where TestClass need to implement marker interface Cloneable
TestClass copy = (TestClass) object.clone();
Above provides the typecasting that is needed to assign the general Object reference that is returned from clone to the reference to a TestClass object.
Please see example below:
package com.javahonk.clonetest; public class CloneTest implements Cloneable{ public static void main(String[] args) throws CloneNotSupportedException { CloneTest cloneTest=new CloneTest(); cloneTest=cloneTest.cloneObject(); System.out.println(cloneTest); } public CloneTest cloneObject() throws CloneNotSupportedException{ CloneTest cloneTest= (CloneTest) super.clone(); return cloneTest; } }