I'm with Jeff . With clone() you can get a copy without knowing the class of the object being copied. There was an article many years ago (I can't find it now) on this subject that came down on the side of clone() but these days I gather the tide has turned. I wonder how the 'prototype' pattern is implemented using copy constructors?
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.
Ritesh raushan wrote:The process of creating an exact copy of an existing copy of an existing object is called cloning...
There are two types of cloning..
Actually there are as many types for a given class as there are combinations of member objects in that class and all its contained objects. We can clone some or all of the members 1, 2, or N layers deep. (Not that we should do that, but the option is there.
But yes, usually we talk only about the two extremes.
1-deep cloning(when the cloned object is modified ,if the original object is not modified,then is called deep cloning).
2-shallow cloning(when the cloned object is modified,same modification will also affect the original object called shallow cloning)...
The modification effects you mention are consequences of the two types of cloning, not the definitions.