CloneDemo.java
Download CloneDemo.java
1: // Demoe of implementing clone. This can be a bit tricky.
2: // Best advice: make your classes immutable, then you don't
3: // need clone. Otherwise, to implement clone, you must
4: // have the class implement the Cloneable interface and
5: // override the clone method. Note, as of Java 5, your clone
6: // method doesn't need to return Object ("covariant return type").
7: // Next, obtain a new object by calling super.clone. This is
8: // important and required by the language, but not enforced by
9: // the compiler. The new object is a "shallow" copy", so replace
10: // all mutable fields with copies. Finally, return the clone.
11: //
12: // In this example, even the ID field is cloned, but in a real
13: // system, there is usually a requirement for unique ID fields
14: // for any object. (This is also an issue for the serialVersionUID.)
15: // Final mutable fields are incompatible with clone.
16: //
17: // In many cases, instead of clone, you can implement a copy constructor:
18: // public CloneDemo ( CloneDemo cd )
19: //
20: // Written 1/2012 by Wayne Pollock, Tampa Florida USA
21:
22: import java.util.Date;
23:
24: public class CloneDemo implements Cloneable
25: {
26: private int id; // primitive field
27: private String name; // immutable object
28: private Date date; // mutable object (danger!)
29:
30: private static int nextId = 0;
31:
32: @Override public CloneDemo clone () throws CloneNotSupportedException
33: {
34: // Create new object:
35: CloneDemo clone = (CloneDemo) super.clone();
36:
37: // replace references to mutable fields:
38: clone.date = (Date) date.clone();
39: return clone;
40: }
41:
42: public CloneDemo ( String name )
43: {
44: id = nextId++;
45: this.name = name;
46: this.date = new Date();
47: }
48:
49: @Override public String toString()
50: {
51: return "ID: " + id + ", NAME: " + name + ", DATE: " + date;
52: }
53:
54: public static void main ( String [] args )
55: {
56: CloneDemo cd1 = new CloneDemo( "Hymie" );
57: CloneDemo cd2 = null;
58: try {
59: cd2 = cd1.clone(); // Old days: cd2 = (CloneDemo) cd1.clone();
60: }
61: catch ( CloneNotSupportedException e )
62: { throw new AssertionError(); // This should never happen
63: }
64: System.out.println( cd1 );
65: System.out.println( cd2 );
66: }
67: }