Explain how to implement Shallow Cloning.

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);

       }

   }

}
Explain how to implement Deep Cloning.
Deep Cloning - Deep cloning makes a distinct copy of each of object’s field...
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...
Post your comment