Monday 24 March 2014

Get the clone of the object : clone()

In Java, objects are manipulated through reference variables, and there is no operator for copying an object—the assignment operator duplicates the reference, not the object. The clone() method provides this missing functionality.

protected Object clone() throws CloneNotSupportedException
Creates and returns a copy of this object. To use clone method for an object, Specific class must implement the Cloneable interface. A class implements the Cloneable interface, to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.

One disadvantage with the design of the clone() method is that the return type of clone() is Object, and needs to be explicitly cast back into the appropriate type. Java1.5 introduces covariant types, this eliminates the need for casting.

Cloning without using Covariant type
class Box implements Cloneable{
 int width, height;
 
 public Object clone()throws CloneNotSupportedException{
   return super.clone();
 }
 
 Box(int width, int height){
  this.width = width;
  this.height = height;
 }
 
}

class ObjectClone{
 public static void main(String args[])throws Exception{
  Box b1 = new Box(10, 20);
  Box b2 = (Box)b1.clone();
  
  System.out.println("\tWidth\t Height");
  System.out.println("b1\t   " + b1.width +"\t" +b1.height);
  System.out.println("b2\t   " + b2.width +"\t" +b2.height);
 }
}

Ouput
         Width    Height
b1         10     20
b2         10     20

As you observe the below statement,
    Box b2 = (Box)b1.clone()
Program did explicit casting. Since the clone method returns the object.

Cloning with using Covariant type
class Box implements Cloneable{
 int width, height;
 
 public Box clone()throws CloneNotSupportedException{
   return (Box)super.clone();
 }
 
 Box(int width, int height){
  this.width = width;
  this.height = height;
 }
 
}

class ObjectClone{
 public static void main(String args[])throws Exception{
  Box b1 = new Box(10, 20);
  Box b2 = b1.clone();
  
  System.out.println("\tWidth\t Height");
  System.out.println("b1\t   " + b1.width +"\t" +b1.height);
  System.out.println("b2\t   " + b2.width +"\t" +b2.height);
 }
}

Output
          Width    Height
b1         10      20
b2         10      20

clone() throws CloneNotSupportedException if the object's class, on which you are calling clone(), does not implement the Clonable interface.

Related Topics
Prevoius                                                 Next                                                 Home

No comments:

Post a Comment