Explain how to implement shallow cloning and deep cloning.
Cloning is a process to create copies of objects.
Implementing Shallow cloning:In shallow cloning, a new object is created which is an exact copy of the original object. It is a bit-wise copy of an object. In case any field of the object is referred to other objects, only the references are copied but not the objects.
For example, an application is using a class by name Car, Person which implements Cloneable interface and another class with public static void main(String args[]) creates object of Person like
Person per1 = new Person(….); Person per2 = (Person) per1.clone();
The following code snippet in Person in the lower level class Person implements the Shallow cloning: public Object clone()
{
//shallow copy
try
{
return super.clone();
}
catch (CloneNotSupportedException e)
{
return null;
}
}
Implementing Deep cloning:
In deep cloning, a duplicate of an object is created, and it is complete. In case any fields of the object is referred to other objects, the fields of duplicate object are copied. It copies not only primitive values of the original object, but also copies the subobjects, all way to the bottom.
Implementing is done by the clone() method of Object class and implemented by Cloneable interface.
The following code snippet implements deep cloning using the Person class described in the above Implementing Shallow cloning section: public Object clone()
{
//Deep copy
Person p = new Person(name, car.getName());
return p;
}