1.比如User类中包含了Address类:
则浅度复制只是复制了User类,并没有复制User里面的Address类;
而深度复制则是两者都复制了;
具体代码如下:
User类:
class User implements Cloneable{
String name = null;
String pwd = null;
Address add = null;
@Override
public String toString() {
return “User [name=” + name + “, pwd=” + pwd + “, add=” + add + “]”;
}
@Override
protected Object clone() throws CloneNotSupportedException {
User user = null;
user = (User)super.clone();//浅度复制
user.add = (Address)add.clone();//深度复制
return user;
}
}
Address 类:
class Address implements Cloneable{
String address = null;
public Address(String address) {
super();
this.address = address;
}
@Override
public String toString() {
return "Address [address=" + address + "]";
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();//浅度复制
}
}
主函数:
public static void main(String[] args) throws Exception {
User t = new User();
t.name = “111”;
t.pwd = “000”;
t.add = new Address(“南湖”);
User tt = (User)t.clone();
tt.pwd="***";
System.out.println(t.toString());
System.out.println(tt.toString());
tt.add.address = “湖”;
System.out.println(t.toString());
System.out.println(tt.toString());
}
}
运行结果: