Topics Index

Exploring java.lang >
Siva Nookala - 20 Feb 2017
The clone method creates a shallow copy of the object on which it is called. Only classes that implements the cloneable interface can be cloned. The cloneable interface defines no members. Its is used to indicate that a class allows a bitwise copy of an object i.e. clone to be made.

Cloning is a potentially dangerous action, because it can cause unintended side effects.
For example, if an object opens an I/O stream and is then cloned, then both of the two objects will be capable of operating on the same stream. Further, if one of these objects closes the stream, then the stream is closed for both and if the second object tries to write to it, this causes an error.
import java.lang.*;

class CloneDemo
    public static void main(String arg[])
        TestClone x1 = new TestClone();
        TestClone x2;
        x1.a = 10;
        x2 = x1.cloneTest(); // clone x1
        x2.b = 20.98;
        System.out.println("x1 : " + x1.a + " " + x1.b);
        System.out.println("x2 : " + x2.a + " " + x2.b);    

class TestClone implements Cloneable

    int a;
    double b;

    //This method calls Object's clone() .    
    TestClone cloneTest()
            //call clone in Object .
            return (TestClone) super.clone(); // LINE A
        } catch (Exception e)
            System.out.println("Cloning not allowed.");
            return this; // LINE B

x1 : value Of a 10 value of b 0.0
x2 : value Of a 10 value of b 20.98


Here, the method cloneTest calls clone method in Object class and returns the result. Notice that the object returned by clone method is of type Object so we have to typecast it to appropriate type like we did at LINE A. If the invoking object class don't implement the Cloneable interface just the reference of the invoking object is returned.

  • Remove TestClone at LINE B to see a compilation error saying Type mismatch: cannot convert from Object to TestClone.
  • Check whether x1 and x2 are equal.
    System.out.println("x1 and x2 are equal : " + x1.equals(x2));
    The output will be x1 and x2 are equal : false since they are two different references of two different objects.
  • Remove the implements Cloneable statement for class TestClone at LINE A and see the output. Also check whether x1 and x2 are equal. The output will be as shown. Cloning not allowed.
    x1 : 10 20.0
    x2 : 10 20.0
    x1 and x2 are equal : true
    Since cloning is not allowed catch block is executed and x1 reference is assigned to x2.

Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App