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:
1 2 3 4 5 |
var = new Employee ("Fawad khan", 50000); Employee Copy = original; copy.raiseSalary (10); // Original changed too! |
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:
1 2 3 |
Employee copy = original.clone (); copy.raiseSalary (10); // Now the original hasn't changed! |
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.)
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Employee implements Cloneable { public Employee clone() throws CloneNotSupportedException { return (Employee) super.clone (); } … } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Employee implements Cloneable { … puЫic Employee clone() throws CloneNotSupportedException { // call method Object.clone() Employee cloned = (Employee) super.clone (); // clone mutable fields cloned.hireDay = (Date) hireDay.clone(); return cloned; } } |
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:
1 |
public Employee clone() throws CloneNotSupportedException |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
import java.util.ArrayList; class varClass{    int x, y; } class getData implements Cloneable {    int a, b;    varClass vc = new varClass();    public Object clone() throws CloneNotSupportedException    {        getData data = (getData)super.clone();        data .vc = new varClass();        return data;    } } public class Demo{    public static void main(String args[])        throws CloneNotSupportedException    {        getData gd1 = new getData();        gd1.a = 100;        gd1.b = 200;        gd1.vc.x = 300;        gd1.vc.y = 400;        getData gd2 = (getData)gd1.clone();        gd2.a = 10;        gd2.vc.x = 30;        System.out.println("before copy: "+gd1.a + " " + gd1.b + " " + gd1.vc.x                           + " " + gd1.vc.y);        System.out.println("after copy: "+gd2.a + " " + gd2.b + " " + gd2.vc.x                           + " " + gd2.vc.y);    } } |
Output:
Example2: How to use the simple java clone() method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
import java.lang.*; class Demo {    public static void main(String arg[])    {        ShowData data1 = new ShowData();        ShowData data2;        data1.a = 100;        data2 = data1.Data();        data2.b = 200.98;        System.out.println("Data1 : " + data1.a + " " + data1.b);        System.out.println("Data2 : " + data2.a + " " + data2.b);      } } class ShowData implements Cloneable {    int a;    double b;         ShowData Data()    {        try        {                       return (ShowData) super.clone();        } catch (Exception e)        {            System.out.println("Cloning not allowed.");            return this;        }    } } |
Output: