Object Cloning Core Java

When you make a copy of a variable, the original and the copy are references to the same object. This means a change to either variable also affects the other.

Copying and cloning

Copying and cloning

If you would like copy to be a new object that begins its life being identical to original but whose state can diverge over time, then you use the clone method.

But it isn’t quite so simple. The clone method is a protected method of Object, which means that your code cannot simply call it. Only the Employee class can clone Employee objects. There is a reason for this restriction. Think about the way in which the Object class can implement clone. It knows nothing about the object at all, so it can make only a field -byfield copy. If all data fields in the object are numbers or other basic types, copying the fields is just fine. But if the object contains references to subobjects, then copying the field gives you another reference to the subobject, so the original and the cloned objects still share some information.

To visualize that phenomenon, let’s consider the Employee class that was introducedbefore. Figure below shows what happens when you use the clone method of the Object class to clone such an Employee object. As you can see, the default cloning operation is“shallow”—it doesn’t clone objects that are referenced inside other objects.

Does it matter if the copy is shallow? It depends. If the subobject that is shared between the original and the shallow clone is immutable, then the sharing is safe. This certainly

happens if the subobject belongs to an immutable class, such as String. Alternatively, the subobject may simply remain constant throughout the lifetime of the object, with no mutators touching it and no methods yielding a reference to it.

A shallow copy

A shallow copy

Quite frequently, however, subobjects are mutable, and you must redefine the clonemethod to make a deep copy that clones the subobjects as well. In our example, the hireDay field is a Date, which is mutable.

For every class, you need to decide whether

  1. The default clone method is good enough;
  2. The default clone method can be patched up by calling clone on the mutable subobjects; and
  3. clone should not be attempted.

The third option is actually the default. To choose either the first or the second option, a class must

  1. Implement the Cloneable interface; and
  2. Redefine the clone method with the public access modifier.

NOTE: The clone method is declared protected in the Object class so that your code can’t simply call anObject.clone(). But aren’t protected methods accessible from any subclass, and isn’t every class a subclass of Object? Fortunately, the rules for protected access are more subtle. A subclass can call a protected clone method only to clone its own objects. You must redefine clone to be public to allow objects to be cloned by any method.

In this case, the appearance of the Clone able interface has nothing to do with the normaluse of interfaces. In particular, it does not specify the clone method—that method is inherited from the Object class. The interface merely serves as a tag, indicating that the Employee class designer understands the cloning process. Objects are so paranoid about cloning that they generate a checked exception if an object requests cloning but does not implement that interface.

NOTE: The Cloneable interface is one of a handful of tagging interfaces that Java provides. (Some programmers call them marker interfaces.) Recall that the usual purpose of aninterface such as Comparable is to ensure that a class implements a particular method orset of methods. A tagging interface has no methods; its only purpose is to allow the use of instanceof in a type inquiry:

We recommend that you do not use tagging interfaces in your own programs.

Even if the default (shallow copy) implementation of clone is adequate, you still need to implement the Cloneable interface, redefine clone to be public, and call super.clone(). Here is an example:

NOTE: Before Java SE 5.0, the clone method always had return type Object. The covariant return types of Java SE 5.0 let you specify the correct return type for your clone methods.

The clone method that you just saw adds no functionality to the shallow copy provided by Object .clone. It merely makes the method public. To make a deep copy, you have to work harder and clone the mutable instance fields.

Here is an example of a clone method that creates a deep copy:

The clone method of the Object class threatens to throw a Clone Not Supported Exception —it does that whenever clone is invoked on an object whose class does not implement the Cloneable interface. Of course, the Employee and Date class implements the Cloneable interface, so the exception won’t be thrown. However, the compiler does not know that. Therefore, we declared the exception:

Would it be better to catch the exception instead?

This is appropriate for final classes. Otherwise, it is a good idea to leave the throws specifier in place. That gives subclasses the option of throwing a Clone Not Supported Exception if they can’t support cloning.

You have to be careful about cloning of subclasses. For example, once you have definedthe clone method for the Employee class, anyone can use it to clone Manager objects. Can the Employee clone method do the job? It depends on the fields of the Manager class. In our case, there is no problem because the bonus field has primitive type. But Manager might have acquired fields that require a deep copy or that are not cloneable. There is no guarantee that the implementor of the subclass has fixed clone to do the right thing. For that reason, the clone method is declared as protected in the Object class. But you don’t have that luxury if you want users of your classes to invoke clone.

Should you implement clone in your own classes? If your clients need to make deep copies, then you probably should. Some authors feel that you should avoid clone altogether and instead implement another method for the same purpose. We agree that clone is rather awkward, but you’ll run into the same issues if you shift the responsibility to another method. At any rate, cloning is less common than you may think. Less than 5 percent of the classes in the standard library implement clone.

The program in Listing below clones an Employee object, then invokes two mutators. The raiseSalary method changes the value of the salary field, whereas the setHireDay method changes the state of the hireDay field. Neither mutation affects the original object because clone has been defined to make a deep copy.

NOTE: All array types have a clone method that is public, not protected. You can use it to make a new array that contains copies of all elements. For example:

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Core Java Topics