1 import java.awt.*; 2 import java.util.Scanner; 3 4 import javax.swing.*; 5 6 public class Test{ 7 public static void main(String[] args) throws CloneNotSupportedException{ 8 House h1 = new House(2,3.5); 9 House h2 = (House)h1.clone(); 10 11 System.out.println("h1 and h2 are equal?"); 12 // System.out.println(h1.getArea()); 13 // System.out.println(h2.getArea()); 14 // System.out.println(h1.getId()); 15 // System.out.println(h2.getId()); 16 // System.out.println(h1.getWhenBuilt()); 17 // System.out.println(h2.getWhenBuilt()); 18 // 19 System.out.println(h1.equals(h2)); 20 } 21 }
1 public class House implements Cloneable{ 2 private int id; 3 private double area; 4 private java.util.Date whenBuilt; 5 6 public int getId() { 7 return id; 8 } 9 10 public double getArea() { 11 return area; 12 } 13 14 public java.util.Date getWhenBuilt() { 15 return whenBuilt; 16 } 17 18 public House(int id, double area) { 19 // TODO Auto-generated constructor stub 20 this.id = id; 21 this.area = area; 22 whenBuilt = new java.util.Date(); 23 } 24 public Object clone() throws CloneNotSupportedException { 25 //override 26 Object ob1 = super.clone(); 27 ((House)ob1).whenBuilt = this.getWhenBuilt(); 28 return ob1; 29 } 30 }