Java Cloneable interface

Introduction

The following program implements Cloneable interface.

// Demonstrate the clone() method.

class TestClone implements Cloneable {
  int a;/*from ww  w.j  a v  a2  s .  co m*/
  double b;

  // This method calls Object's clone().
  TestClone cloneTest() {
    try {
      // call clone in Object.
      return (TestClone) 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 = 1;
    x1.b = 2.0;

    x2 = x1.cloneTest(); // clone x1

    System.out.println("x1: " + x1.a + " " + x1.b);
    System.out.println("x2: " + x2.a + " " + x2.b);
  }
}



PreviousNext

Related