1) Resources
Cloneable Interface in Java
Java Cloning Tutorial, Shallow Copy and Deep Copy
http://www.javaexperience.com/java-cloning-tutorial/
A guide to object cloning in java
How to implement Cloneable Interface
Implementing Cloneable interface
clone() and the Cloneable Interface in Java
How to implement cloning in java using Cloneable interface?
About Java cloneable
What is the use of cloneable interface in java?
Implementing the Cloneable Interface
How clone method works in Java
2) CloneNotSupportedException example
A clone of an object is an object with distinct identity and equal contents. To define clone, a class must implement cloneable interface and must override Object’s clone method with a public modifier. At this point, it is worth nothing that cloneable interface does not contain the clone method, and Object’s clone method is protected.When the Object class finds that the object to be cloned isn’t an instance of a class that implements cloneable interface, it throws CloneNotSupportedException.
3) Standard clonning
If a class wants to allow clients to clone it’s instances, it must override Object’s clone method with a public modifier.If you override the clone method in a non final class, you should return an object obtained by invoking super.clone. If all of a class’s super classes obey this rule, then invoking super.clone will eventually invoke Object’s clone method, creating an instance of the right class.
4) Clonning complex object
Once you get hold of object from super.clone(), we may have to do some modifications depending on nature of the classIf every field contains a primitive value or a reference to an immutable object, no further processing is necessary. If there are references to mutable objects, in order to work clone properly, it is required to call clone on those mutable references.
If there are final fields referring to mutable objects, In order to make a class cloneable, it may be necessary to remove final modifiers from some fields.
If you decide to make a thread-safe class implement Cloneable, remember that its clone method must be properly synchronized just like any other method
Example to clone mutable references
Sir thanks for sharing links on cloneable interface. Understood the concept.
ОтветитьУдалитьCheers,
http://www.flowerbrackets.com/java-clone/
Nice article . There is good coding example collection visit
ОтветитьУдалитьTop coding program example