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.
public static void main(String arg)
TestClone x1 = new TestClone();
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
//This method calls Object's clone() .
//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
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
LINE B to see a compilation error saying Type mismatch: cannot convert from Object to TestClone.
- 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