Menu
Topics Index
...
`

CloneDemo - Java Example Program


CloneDemo
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()
    {
        try
        {
            //call clone in Object .
            return (TestClone) super.clone(); // LINE A
        } catch (Exception e)
        {
            System.out.println("Cloning not allowed.");
            return this; // LINE B
        }
    }
}
OUTPUT

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

DESCRIPTION

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.

THINGS TO TRY
  • 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.

© meritcampus 2019

All Rights Reserved.

Open In App