/home/wpollock1/public_html/AJava/CloneDemo.java
// Demoe of implementing clone. This can be a bit tricky.
// Best advice: make your classes immutable, then you don't
// need clone. Otherwise, to implement clone, you must
// have the class implement the Cloneable interface and
// override the clone method. Note, as of Java 5, your clone
// method doesn't need to return Object ("covariant return type").
// Next, obtain a new object by calling super.clone. This is
// important and required by the language, but not enforced by
// the compiler. The new object is a "shallow" copy", so replace
// all mutable fields with copies. Finally, return the clone.
//
// In this example, even the ID field is cloned, but in a real
// system, there is usually a requirement for unique ID fields
// for any object. (This is also an issue for the serialVersionUID.)
// Final mutable fields are incompatible with clone.
//
// In many cases, instead of clone, you can implement a copy constructor:
// public CloneDemo ( CloneDemo cd )
//
// Written 1/2012 by Wayne Pollock, Tampa Florida USA
import java.util.Date;
public class CloneDemo implements Cloneable
{
private int id; // primitive field
private String name; // immutable object
private Date date; // mutable object (danger!)
private static int nextId = 0;
@Override public CloneDemo clone () throws CloneNotSupportedException
{
// Create new object:
CloneDemo clone = (CloneDemo) super.clone();
// replace references to mutable fields:
clone.date = (Date) date.clone();
return clone;
}
public CloneDemo ( String name )
{
id = nextId++;
this.name = name;
this.date = new Date();
}
@Override public String toString()
{
return "ID: " + id + ", NAME: " + name + ", DATE: " + date;
}
public static void main ( String [] args )
{
CloneDemo cd1 = new CloneDemo( "Hymie" );
CloneDemo cd2 = null;
try {
cd2 = cd1.clone(); // Old days: cd2 = (CloneDemo) cd1.clone();
}
catch ( CloneNotSupportedException e )
{ throw new AssertionError(); // This should never happen
}
System.out.println( cd1 );
System.out.println( cd2 );
}
}