1、为什么要重写clone()方法?
答案:Java中的浅度复制是不会把要复制的那个对象的引用对象重新开辟一个新的引用空间,当我们需要深度复制的时候,这个时候我们就要重写clone()方法。
2、为什么要重载equal方法?
答案:因为Object的equal方法默认是两个对象的引用的比较,意思就是指向同一内存,地址则相等,否则不相等;如果你现在需要利用对象里面的值来判断是否相等,则重载equal方法。
House类:
01 | package house; |
02 |
03 | import java.util. Date ; |
04 |
05 | public class House implements Cloneable { |
06 |
07 | private int id; |
08 | private double area; |
09 | private Date whenBulit; |
10 |
11 | House(){ |
12 |
13 | } |
14 |
15 | House(int newId,double newArea){ |
16 | id = newId; |
17 | area = newArea; |
18 | whenBulit = new Date (); |
19 | } |
20 |
21 | public int getId() { |
22 | return id; |
23 | } |
24 |
25 | public void setId(int id) { |
26 | this.id = id; |
27 | } |
28 |
29 | public void setArea(double area) { |
30 | this.area = area; |
31 | } |
32 |
33 | public void setWhenBulit(long whenBulit) { |
34 |
35 | this.whenBulit.setTime(whenBulit) ; |
36 | } |
37 |
38 | public double getArea() { |
39 | return area; |
40 | } |
41 |
42 | public Date getWhenBulit() { |
43 | return whenBulit; |
44 | } |
45 |
46 | public long getWhenBulitTime() { |
47 | return whenBulit.getTime(); |
48 | } |
49 |
50 | //重写equals方法,因为我们要对比的是date类中的时间而不是对象的引用地址 |
51 | //如果传递的是Object类的话,我们就需要重写hashCode()方法,这样就比较麻烦 |
52 | public boolean equals(House obj){ |
53 | if (obj.getArea()==this.getArea()&&obj.getId()==this.getId()&&obj.getWhenBulitTime()==this.getWhenBulitTime()) |
54 | return true; |
55 | else |
56 | { |
57 | return false; |
58 | } |
59 |
60 | } |
61 |
62 | public Object clone() throws CloneNotSupportedException{ |
63 |
64 | House house = new House(this.getId(),this.getArea()); |
65 | house.setWhenBulit(this.getWhenBulit().getTime()) ; |
66 | return house ; |
67 | } |
68 |
69 | } |
Testor类:
01 | package house; |
02 |
03 | public class Testor { |
04 |
05 | public static void main(String[] args ) throws CloneNotSupportedException{ |
06 |
07 | House h1 = new House(1,200.0); |
08 |
09 | House h2 = (House)h1.clone(); |
10 |
11 | System.out.println(h1==h2); |
12 | System.out.println(h1.equals(h2)); |
13 |
14 | System.out.println(h1.getWhenBulit()==h2.getWhenBulit()); |
15 |
16 | System.out.println(h1.getWhenBulit().equals(h2.getWhenBulit())); |
17 |
18 | } |
19 |
20 | } |