使用Java语言设计一个客户类Customer,其中客户地址存储的地址类Address中,用浅克隆和深克隆分别实现Customer对象的复制并比较这两种克隆方式的异同。绘制类图并编程实现。
时间: 2023-11-27 08:52:43 浏览: 87
以下是使用Java语言设计的客户类Customer及其关联的地址类Address的完整实现。其中,浅克隆方式只克隆了地址对象的引用,而深克隆方式则复制了一个新的地址对象。
```java
// Address类
public class Address implements Cloneable {
private String street;
private String city;
private String state;
private String zip;
public Address(String street, String city, String state, String zip) {
this.street = street;
this.city = city;
this.state = state;
this.zip = zip;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
@Override
public Address clone() throws CloneNotSupportedException {
return (Address) super.clone();
}
}
// Customer类
public class Customer implements Cloneable {
private String name;
private Address address;
public Customer(String name, Address address) {
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
// 浅克隆
@Override
public Customer clone() throws CloneNotSupportedException {
return (Customer) super.clone();
}
// 深克隆
public Customer deepClone() throws CloneNotSupportedException {
Customer cloned = (Customer) super.clone();
cloned.setAddress(cloned.getAddress().clone());
return cloned;
}
}
```
对于浅克隆和深克隆的比较,我们可以编写以下测试代码:
```java
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
Address address = new Address("123 Main St.", "Anytown", "CA", "12345");
Customer customer1 = new Customer("John Doe", address);
// 浅克隆
Customer customer2 = customer1.clone();
System.out.println(customer1 == customer2); // false
System.out.println(customer1.getAddress() == customer2.getAddress()); // true
// 深克隆
Customer customer3 = customer1.deepClone();
System.out.println(customer1 == customer3); // false
System.out.println(customer1.getAddress() == customer3.getAddress()); // false
}
}
```
在浅克隆方式下,克隆出来的Customer对象和原对象不是同一个对象,但是它们所引用的Address对象是同一个对象。而在深克隆方式下,克隆出来的Customer对象和原对象也不是同一个对象,但是它们所引用的Address对象却不是同一个对象。由此可以看出,深克隆方式比浅克隆方式更加安全,但是也更加耗费资源。