In this article we discuss the Cloneable interface that indicates that a class has provided a safe clone() method. To understand what cloning means recall what happens when you make a copy of a variable holding an object reference. The original and the copy are references to the same object. This means the original and the copy are mutually dependent, i.e., a change in one causes a change in the other as well.
If we would like a copy to be a new object that begins its life being identical to the original but whose state can change over time we must use the clone() method.
The clone() method is declared protected in the Object class, so our code can’t simply call obj.clone(). Now we might ask, 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 much more subtle. A subclass can call protected clone() method to clone its own objects. We must redefine clone to be public to be accessed by any methods.
The clone() method that you just saw adds no functionality to the copy provided by Object.clone. It merely makes the method public and changes its return type. To make a deeper copy, we must clone the mutable instance fields.
This is the modified version:
The clone() method of Object will try to throw a ClassNotSupportedException whenever clone is invoked on a class that does not implement the Cloneable interface.
original= Employee[name=ABC X. YZ, salary=50000.0, hireDay=Sat Jan 01 00:00:00 UTC 2000]
copy= Employee[name=ABC X. YZ, salary=55000.0, hireDay=Tue Dec 31 00:00:00 UTC 2002]
Advantages of Cloning:
- In Java, the ‘=’ (assignment) operator cannot be used for cloning as it simply creates a copy of reference variables. To overcome such discrepancy the clone() method of Object class can be used over assignment operator.
- The clone() method is protected method of class Object which means that only Employee class can clone Employee objects. This means no class other than Employee can clone Employee objects since it does not know Employee class’ attributes.
Application of Cloning in Java:
- It allows field-by-field copying of objects which comes handy when dealing with objects of similar characteristics.
- The default clone() method can be patched up by calling clone on mutable subobjects.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.