Java Clone Method with Programming Examples

Description:

Java clone method with programming examples:-  in this article, I am going to show you how to use a clone method in java programming with step by step explanation.


Java Cloning objects using interface:

The Cloneable interface, which means that a robust java clone() method is provided in the class. Object cloning is done infrequently, and the details of this process are completely technical in nature, therefore, you may not refer to the material in this section as long as until you need it.

To understand the purpose of cloning objects, recall what happens when a copy of the variable containing the object reference is made. In this case, the original and the copy of the variable contain references to the same object (see in the below figures). it means that changing one variable will change another:

java Clone method

java Clone method

java Clone method



If you want the variable swap to represent a new object that at the first moment of its existence is identical to the original object, but completely is independent of it, in this case, you need to use the Java clone() method as follows way:

But not everything is so simple. The java clone() method is protected in the class Object, i.e. it cannot be called directly. And only the Employee class can clone objects of their class. There is a good reason for this limitation. Let’s analyze how the Object class can implement the Java clone() method. nothing is known about the object at all, so it can only copy fields. If a all class fields are numeric or have a different basic type, copying them runs fine. But if the object contains a reference to a sub-object, then the order and cloned objects will share the same data.

To illustrate this phenomenon, consider the Employee class, which,, we use with objects. In figure showing what happens when a java clone() method is from a class Object is used to clone an object of type Employee. As you can see, the operation cloning by default is incomplete – it does not clone objects, which are referenced in other objects. (below figure shows a generic object Date. For reasons that will become clear in what follows, in this example, we use a variant of the Employee class in which the day of hiring is represented by an object of type Date.)

java Clone method

Is incomplete copying really bad? It all depends on the specific situation. If a subobject is shared with both the original and the incomplete clone, is unchangeable, it is completely safe. This happens if the node object is an instance of an immutable class such as String. On the other hand, a subobject can remain constant for the entire duration of that the object that contains it without being exposed to modifying methods or methods that compute a reference to it.

But subobjects are often subject to change, so you have to override java clone() method to do a full copy, which allows clone subobjects along with their containing objects. In this example the hireDay field refers to an instance of a mutable Date class, and therefore it must also be cloned. (This uses a field of type Date, not of type LocalDate specifically to demonstrate the specifics of the cloning process. If the hireDay field referenced an instance of an immutable class LocalDate, no further action would be required.)


For each class, the following decisions need to be made.

  • Is the default java clone() method sufficient?
  • Is it possible to modify the default clone() method like this way to call it on mutable objects?
  • Should you skip the java clone() method altogether?

The last decision is taken by default. And for the adoption of the first and second class solutions must meet the following requirements.

  • Implementation of the Cloneable interface.
  • Overriding the clone() method with the public access modifier.

In this case, the java Cloneable interface is used in an unusual way. In particular, the  Java clone() method is not declared in it, but inherits from the Object class. The interface serves as a label indicating that, in this case, the developer class understands how the cloning process is done. In the Java language there is so wary of cloning objects that if an object requires this operation, but does not implement the java Cloneable interface, it is generated an exception.

Even though the default implementation of the java clone() method (incomplete copy) is quite suitable, you still need to implement the Cloneable java interface as well, redefine clone() method as public and make a call to super. clone() as shown in the following code example:


The above clone() method does not add any new functionality. possibilities to the Object method. clone(), which implements incomplete copying. It will take extra effort to make a full copy and organize the cloning of the mutable fields of the instance. Below is an example of the implementation of the clone() method that performs a full copy.

The java clone() method from the Object class can throw an exception like CloneNotSupportedException. This happens when the clone() method is called for an object that does not implement the Cloneable interface. But since the classes Employee and Date implement this interface, no exception is thrown. However, the compiler knows nothing about this, and therefore about a possible exception have to be declared like this:

Special care should be taken when cloning objects of subclasses. So, if you define a java clone() method in the Employee class, others can use them to clone objects of type Manager. Will the clone() method from the class Employee cope with a similar task? The ego depends on the set of fields declared in the Manager class. In this case, no difficulties arise, since the field bonus is of primitive type. But after all, the Manager class can be entered a field that requires full copying or does not allow cloning at all. There is no guarantee that the subclass implements a clone() method that correctly resolves the assigned task.

That is why the java clone() method is declared in the Object class as protected. But if you want users of your classes to be able to call the clone() method, this luxury remains unavailable to you.

Should I implement the clone() method in my classes? If user’s full copying is required, the answer, of course, must be yes. Some experts believe that the java clone() method should be abandoned altogether and instead, implement another method that solves a similar problem. Can, of course, to agree that the java clone() method is not a very good solution, but if you transfer its functions to another method, you will face the same difficulties. Be that as it may, cloning is rarely used. Suffice it to say that the method clone() is implemented in less than 5% of the classes in the standard library.


Programming Examples:

Example1:  How to use java clone() method for deep copying:

Output:

java Clone method



Example2: How to use the simple java clone() method:

 

Output:

java Clone method

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: