Using clone( ) and the Cloneable Interface

The clone( ) method generates a duplicate copy of the object. Only classes that implement the Cloneable interface can be cloned. If you try to call clone( ) on a class that does not implement Cloneable, a CloneNotSupportedException is thrown.

clone() is declared as protected inside Object.
Let's look at an example of each approach.
The following program implements Cloneable and defines the method cloneTest(), which calls clone() in Object:
 
class TestClone implements Cloneable {
  int a;
  public Object clone() {
    try {
      return super.clone();
    } catch (CloneNotSupportedException e) {
      System.out.println("Cloning not allowed.");
      return this;
    }
  }
}
public class Main {
  public static void main(String args[]) {
    TestClone x1 = new TestClone();
    TestClone x2;
    x1.a = 10;
    // here, clone() is called directly.
    x2 = (TestClone) x1.clone();
    System.out.println("x1: " + x1.a);
    System.out.println("x2: " + x2.a);
  }
}

The output:


x1: 10
x2: 10
Home 
  Java Book 
    Class  

Object class:
  1. The Object Class
  2. Using clone( ) and the Cloneable Interface