clone is not copy constructor

what does Cloneable do? Its a marker interface that has no methods and implementing class is saying that if you call a clone method and in the super.clone chain it ends up calling clone method of Object class it’ll no throw CloneNotSupportedException, and return field-by-field (shallow) copy of the object. Most important thing is the object return by Object.clone is __not__ created by constructor (and may be that’s why its a native method in Object class) so all the invariants constructor forces to ensure validity of the object will not be applied.

****** ****** ******
Object.clone will return shallow copy of the object in its __current__ state if the Class of the object this method has been called on implements Cloneable interface otherwise it throws CloneNotSupportedException
****** ****** ******

Cloneable is an interface that defines the behaviour of a protected method (clone) of a class (Object), very innovative use of an interface, isn’t it.

if object is immutable there is __no__ need to clone it, because cloned instance is indistinguishable from original instance. If object is mutable “shallow copy” might be a big mistake. Then what’s the point Cloneable is trying to make?

And if a class implement Cloneable interface and implement clone method to support __deep__ copy, it can not reassign final fields because clone method is not constructor, implies if you want to deep copy a final field in clone method you can not do that and make it non-final.

2 solutions suggested by Mr Bloch in item 11–
1. Factory method

public static Yum newInstance(Yum yum)

2. Copy constructor

public Yum(Yum yum)

http://www.artima.com/intv/bloch14.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s