How do we implement deep cloning?

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;
       }
     }
  }
}
Java features
Java features - Simple, Object-Oriented, Robust, Distributed, Portable, Interpreted, Multithreaded, Platform Independent, Secure...
Java program execution
Java program execution - What is JVM? Explain its roles and functions, Why Java is called as Platform independent language. How Java executable executes on any platform where JVM is available...
Java architecture
Java architecture - Java programming language, Java class file format, Java Application Programming Interface, Java virtual machine...
Post your comment