Java Clone, Shallow Copy and Deep Copy
Clone (κλών) is a Greek word meaning “branch”, referring to the
process whereby a new plant can be created from a twig. In biology it is
about copying the DNAs. In real world, if you clone Marilyn Monroe,
will you get a copy of her with same beauty and characteristics? No, you
will not get! This exactly applies to java also. See how java guys are
good at naming technologies.
In java, though clone is ‘intended’ to produce a copy of the same
object it is not guaranteed. Clone comes with lots of its and buts. So
my first advice is to not depend on clones. If you want to provide a
handle / method to deliver a copy of the current instance write a kind
of factory method
and provide it with a good documentation. When you are in a situation
to use a third party component and produce copies of it using the clone
method, then investigate that implementation carefully and get to know
what is underlying. Because when you ask for a rabbit, it may give
monkeys!
Since the Object class has the clone method (protected) you cannot use it in all your classes. The class which you want to be cloned should implement clone method and overwrite it. It should provide its own meaning for copy or to the least it should invoke the super.clone(). Also you have to implement Cloneable marker interface or else you will get CloneNotSupportedException. When you invoke the super.clone() then you are dependent on the Object class’s implementation and what you get is a shallow copy.
Shallow Copy
Generally clone method of an object, creates a new instance of the same class and copies all the fields to the new instance and returns it. This is nothing but shallow copy. Object class provides a clone method and provides support for the shallow copy. It returns ‘Object’ as type and you need to explicitly cast back to your original object.Since the Object class has the clone method (protected) you cannot use it in all your classes. The class which you want to be cloned should implement clone method and overwrite it. It should provide its own meaning for copy or to the least it should invoke the super.clone(). Also you have to implement Cloneable marker interface or else you will get CloneNotSupportedException. When you invoke the super.clone() then you are dependent on the Object class’s implementation and what you get is a shallow copy.
0 comments:
Post a Comment