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:
OR we do casting where TestClass need to implement marker interface Cloneable
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: