Sunday, 4 June 2017

Cloning with Cloneable interface


Cloning is the process of making copy of an object. To enable cloning of a class we have to do following
1.Implements the cloneable interface
2.Override the clone method from Object class.

Clone object must follow below characteristic
1.O1.clone()!=O1 
This implies that they original object and cloned object are in different heap space.
2.O1.clone().getClass()==O1.getClass
    This implies that both the original and the cloned object are of same type but this is not an absolute requirement
3.O1.clone().equals(O1)
This implies that original and cloned object are equal but this is no ant absolute requirement.

Shallow Cloning
Shallow cloning is the default behavior of cloning where there is bitwise copying of original object   to generate cloned object. This means all the primitive variable are copied by value while any inner object are copied by reference. This has the implication that original and cloned object share the same inner object. Hence any change in the inner object by original impacts cloned object and vice verse. 



 Illustration





    Test class: 



Default implementation of cloning should be used when the member of cloneable class are of primitive type or immutable object. 


Deep cloning
If we want that original and cloned object are completely independent of each other we have to implement deep cloning. 




Illustration
Note the change in implementation of clone method of Person class.













Also note that inner object Address now implement cloneable interface and also provide implementation for the clone method. 
This has implication that for deep cloning all the nested class should implement cloneable interface and also provide implementation for clone();


 

Test class will remain same and we get the below result.



Resources

No comments:

Post a Comment

Streaming with Kafka API

The Kafka Streams API is a Java library for building real-time applications and microservices that efficiently process and analyze large-sca...