// // a first try at implementing Cloneable // class Try1 implements Cloneable { int single ; int[] pair = new int[2] ; Try1(int a, int b, int c) { single = a ; pair[0] = b ; pair[1] = c ; } // override this method of Object class to provide nice // printing public String toString() { return single + " " + pair[0] + " " + pair[1] ; } // provide this method to implement Cloneable public Object clone() { try { // use Object class clone() return super.clone() ; } catch (CloneNotSupportedException e) { throw new Error("This should not happen!") ; } } } // // a second (better) try at implementing Cloneable // class Try2 implements Cloneable { int single ; int[] pair = new int[2] ; Try2(int a, int b, int c) { single = a ; pair[0] = b ; pair[1] = c ; } // override this method of Object class to provide nice // printing public String toString() { return single + " " + pair[0] + " " + pair[1] ; } // provide this method to implement Cloneable public Object clone() { try { // note typecasts Try2 copy = (Try2) super.clone() ; copy.pair = (int [])pair.clone() ; return copy ; } catch (CloneNotSupportedException e) { throw new Error("This should not happen!") ; } } } public class Clones { public static void main(String[] args) { // try the first way System.out.println("First try at cloning:") ; Try1 x1 = new Try1(1, 2, 3) ; Try1 x2 = (Try1) x1.clone() ; // note typecast System.out.println("x1 = " + x1) ; System.out.println("x2 (clone of x1) = " + x2) ; System.out.println("Changing x1") ; x1.single = 10 ; x1.pair[0] = 20 ; System.out.println("x1 = " + x1) ; System.out.println("x2 = " + x2) ; // try the second way System.out.println("") ; System.out.println("Second try at cloning:") ; Try2 y1 = new Try2(1, 2, 3) ; Try2 y2 = (Try2) y1.clone() ; // note typecast System.out.println("y1 = " + y1) ; System.out.println("y2 (clone of y1) = " + y2) ; System.out.println("Changing y1") ; y1.single = 10 ; y1.pair[0] = 20 ; System.out.println("y1 = " + y1) ; System.out.println("y2 = " + y2) ; } }