Clone method, cloneable interface, cloning of objects, limitations in Java

clone( ) method: It is used to create a new object same as calling object. The new object will be an exact copy of the original object.


Object clone( ) throws CloneNotSupportedException

Cloneable interface: A cloneable interface suggests that cloning can be done for a class. It has no members. Only classes that implement cloneable interface are cloned. If a class does not implement a cloneable intrface and if you try running a clone method in that class then CloneNotSupportedException exception is thrown.

Limitations of cloning:

1) Reference variable of original objects creates a reference to the clone object also. If clone changes the referred object, then changes are also made to original object.

2) If either a cloned object or the original object open an input or output stream, both can operate on same stream.

Solution: Because of the above given problems, with cloning, clone( ) method is always declared as protected inside the Object.

Leave a Reply