Java provides the clone()
method in the Object
class, which is used to clone an object. The clone()
method is a native method and thus provides a shallow copy of the object, specially when they are complex. This method provides functionality where you can get a duplicate copy of an object.
Here is an example of using the clone()
method:
class Demo implements Cloneable {
String demoString;
public Demo(String demostr) {
this.demoString = demostr;
}
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Test {
public static void main(String args[]) {
Demo demo1 = new Demo("Test");
try {
Demo demo2 = (Demo) demo1.clone();
System.out.println(demo2.demoString);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
In this example, demo1
object is cloned and the new demo2
object contains the exact same string. The clone method is protected, so you must override it to increase its visibility and properly use it.
It's crucial to implement the Cloneable
interface if you're to use the clone() method. Otherwise, it throws CloneNotSupportedException
. Implementing Cloneable
interface is necessary, it indicates that the user can safely perform cloning operation.
The important thing to note while cloning in Java is that it is a shallow copy. In the context of object cloning, shallow and deep cloning are two terms used to describe the level of duplication. Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the original object’s values. If the original object contains a reference to an object, the clone will also contain a reference to the same object, not a new object with the same contents.
For a deep copy, you might need to implement it manually or use third-party libraries. Be aware that sometimes, improper use of cloning might lead to vulnerabilities or bugs in your system.
Understanding and using the clone()
method effectively in Java helps handle object copies better in memory, and can be especially useful in scenarios where you need independent copies of objects in memory. The understanding of clone()
is a good part of mastering your Java object handling capabilities.