Explain how to implement Shallow Cloning.
Generally cloning means creating a new instance of a same class and copy all the fields to the new instance. This is called shallow cloning. A property of shallow copies is that fields that refer to other objects will point to the same objects in both the original and the clone. The object class has the clone method which is protected hence it cannot be used directly in all the classes. The class which user wants to clone must implement the clone method and overwrite it. A cloneable interface is implemented first unless an exception is created.
For Example:class students implements Cloneable
{
private String name;
private String branch;
public students()
{
this.setName("RAM");
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
}
public String getBranch()
{
return branch;
}
public void setBranch(String branch)
{
this.branch=branch;
}
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}
public class cloneExample
{
public static void main(String args[])
{
students obj=new students();
obj.setBranch ("IT");
try
{
students obj1=(students) obj.clone();
System.out.println(obj1.getBranch());
System.out.println(obj1.getName());
}
catch(CloneNotSupportedException e)
{
System.out.println(e);
}
}
}