What is cloning? Explain how to design a class that supports cloning.
If you create an object on the heap and assign the object to another object, then the compiler does not create another object. Only the reference of that object is assigned to the other.
Example: A a = new A();
A b = new B();
Then b = a, will not create a new object for b. b will just be assigned the reference to the object.
In Java, there is no direct way to copy the contents of an object into a new object.
Thus to be able to copy the objects into another one, the clone method can be used.
While cloning, following things should be remembered:1. Implement the Clonable interface.
2. Override implementation of the clone() method of the object class.
3. Make the clone method in your class public.
4. Your first statement in the clone method should be super.clone().
Example: class A implements Cloneable
{
...
public Object clone()
{
try
{
return super.clone();
}
catch( CloneNotSupportedException e )
{
System.out.println("CloneNotSupportedException");
}
}
...
}
Note: The default implementation of Object.clone only performs a shallow copy.