How do we implement deep cloning?
Deep cloning makes a distinct copy of each of object’s field. By this the two objects are not dependent on each other. Serialization is used in deep cloning. Serializable class is implemented for this.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class students implements Cloneable,
Serializable
{
private String name;
private String branch;
public Counter counter;
public students(String name, String branch)
{
this.name = name;
this.branch = branch;
this.counter = new Counter();
}
public Object clone() throws CloneNotSupportedException
{
students obj = (students) super.clone();
Object object = null;
try
{
object = getstudents(obj);
counter.setcounter(3);
}
catch (Exception e)
{
e.printStackTrace();
}
return object;
}
public Object getstudents(Object obj) throws IOException, ClassNotFoundException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
}
public static void main(String[] args)
{
students obj = new students("RAM", "IT");
try
{
obj = (students)obj.clone();
System.out.println("in new clone object "+ obj.counter.getcounter());
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
}
class Counter implements Serializable
{
public int counter = 0;
public Counter()
{
counter++;
}
public int getcounter()
{
return counter;
}
public void setcounter(int i)
{
counter = i;
}
}
}
}