The Clone method

The clone method is a protected method in class Object. Therefore object.clone() is visible to only its subclasses which is every class in the Java hierarchy.

Also note that there is a marker interface: Cloneable; which specifies if the instances of the classes implementing this interface can be cloned or not => if the clone method can be invoked on them.

What is a shallow copy/clone of an object:

A shallow copy comes into play if the object to be cloned references other objects. The shallow copy will reference the same objects and not copies of them. If the object to be cloned referenced primitives or immutable objects then the cloning behavior provided by invoking Object.clone() in a derived class would lead to a deep copy/cloning.

A shallow copy means that the copy object itself is different, but if the original object referenced other objects, the copy will reference those same objects, and not a copy of them. 

How does it work:

The subclass needs to override the Object.clone() by providing a public clone() method. Also, the marker Cloneable interface also needs to be implemented. The first call in the overridden clone method should be super.clone() and that ultimately travels up to Object.clone().

The object.clone() does a byte by byte (or whatever the word size is) copy of the classes in the hierarchy. This leads to shallow cloning for reference types since the references are copied into the newly cloned instance. It would be a good idea for the overriding clone method in the derived classes to provide for any deeper cloning if necessary.

 Why use a copy constructor if clone is present:

Final fields in a class cannot be set to a value once the clone has been created therefore a copy constructor might be needed.

Leave a Reply

Your email address will not be published. Required fields are marked *

     

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">