使用场景:
(1)类初始化需要消耗非常多的资源时,通过拷贝可以避免一些消耗;
(2)通过new对象需要非常繁琐的数据准备或者访问权限时;
(3)一个对象需要提供给其他对象访问,而且各个对象可能需要修改其值时,可保护性拷贝(浅拷贝和深拷贝)
private void test(){
address = new Address("gz","th","sp");
user = new User(10,"jack","18138780689",address);
Log.e(TAG,user.toString());
try {
userClone = user.clone();
Log.e(TAG,userClone.toString());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
userClone.address.city = "sz";
userClone.phoneNum = "18028512904";
Log.e(TAG,userClone.toString());
Log.e(TAG,user.toString());
}
'''
public class Address implements Cloneable{
public String city;
public String district;
public String street;
public Address(String city, String district, String street) {
this.city = city;
this.district = district;
this.street = street;
}
@Override
public String toString() {
return "Address{" +
"city='" + city + '\'' +
", district='" + district + '\'' +
", street='" + street + '\'' +
'}';
}
@Override
protected Address clone() throws CloneNotSupportedException {
return (Address) super.clone();
}
}
'''