//DatesCloneableTest.java //demo clone() and Cloneable //do not use for 241. copy ctor can accomplish what clone() does. //Date and IncDate are in this file for a standalone demo program. import java.util.*; import javax.swing.*; public class DatesCloneableTest { public static void main(String[] args) { IncDate date1 = new IncDate(12,23,2000); System.out.println("date1 starts: " + date1); IncDate date2; date2 = date1; System.out.println("date2 also starts: " + date2); //date2 is a reference to the same object that date1 is a reference to. //date1 and date2 are aliases of each other. date2.increment(); //changing date2, System.out.println("date2 is now: " + date2); System.out.println("date1 also is now: " + date1); //changes date1 IncDate date3; //clone() returns Object, so need to cast to IncDate date3 = (IncDate)date1.clone(); //a copy of date1, not an alias System.out.println(); System.out.println("date3 starts: " + date3); date3.increment(); System.out.println("date3 is now: " + date3); System.out.println("date1 is still: " + date1); //does NOT change date1 System.exit(0); } } //***Date class overrides clone() method of Object class Date implements Cloneable //same as in ch01. ***added clone() { protected int year; protected int month; protected int day; public Date(int newMonth, int newDay, int newYear) { month = newMonth; day = newDay; year = newYear; } //***override clone method of Object and make it public (is protected in Object) //***must be this signature: public Object clone() { //must be try and catch of CloneNotSupportedException try { //call clone in Object which does shallow copy only. //if class has references need deep copy; has to be more complex... return super.clone(); } catch ( CloneNotSupportedException e) { System.out.println("Cloning not allowed?!?!?"); return this; } } public int yearIs() { return year; } public int monthIs() { return month; } public int dayIs() { return day; } public String toString() { return(month + "/" + day + "/" + year); } } class IncDate extends Date //same as in ch01 { public IncDate(int newMonth, int newDay, int newYear) { super(newMonth, newDay, newYear); } public void increment() { // increment algorithm goes here // it updates the year, month, and day attributes day = day + 1; } }