Cloning an object is to copy the object bit by bit.
To clone objects in Java, reimplement the clone() method in your class.
The declaration of the clone() method in the Object class is as follows:
protected Object clone() throws CloneNotSupportedException
clone() method is declared protected. You need to declare the clone() method public in your class if you want the client code to clone objects of your class.
Its return type is Object. You need to cast the returned value of the clone() method.
The clone() method in the Object class throws a CloneNotSupportedException.
When calling the clone() method of the Object class, place the call in a try-catch block, or rethrow the exception.
The following code shows how to implement your own clone() method.
YourClass obj = null; try { // Call clone() method of the Object class using super.clone() obj = (YourClass)super.clone(); } catch (CloneNotSupportedException e) { e. printStackTrace(); } return obj;
The following code creates a DoubleHolder class and overrides the clone() method of the Object class.
class DoubleHolder implements Cloneable { private double value; public DoubleHolder(double value) { this.value = value; }//from w ww . ja va2s . c o m public void setValue(double value) { this.value = value; } public double getValue() { return this.value; } public Object clone() { DoubleHolder copy = null; try { copy = (DoubleHolder) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return copy; } } public class Main { public static void main(String[] args) { DoubleHolder dh = new DoubleHolder(100.00); // Clone dh DoubleHolder dhClone = (DoubleHolder) dh.clone(); // Print the values in original and clone System.out.println("Original:" + dh.getValue()); System.out.println("Clone :" + dhClone.getValue()); // Change the value in original and clone dh.setValue(200.00); dhClone.setValue(400.00); // Print the values in original and clone again System.out.println("Original:" + dh.getValue()); System.out.println("Clone :" + dhClone.getValue()); } }