Explain how to implement Deep Cloning.

Explain how to 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)

       {

           // TODO Auto-generated catch block

           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;

   }

}
Scheduling and Priority works in threads
Scheduling and Priority works in threads - Threads are assigned priorities that the thread scheduler can use to determine how the threads will be treated...
Single threaded model in servlets.
Single threaded model in servlets - A servlet class is instantiated the first time it is invoked. The same instance will be used over several client requests...
Can you explain how Java interacts with database?
How Java interacts with database? - Java interacts with database with the help of JDBC means Java Database Connectivity...
Post your comment