Java Object类中clone()方法的使用(浅克隆,深克隆)
public class Test09013Object {
public static void main(String[] args) throws CloneNotSupportedException {
Boy boy =new Boy("小明");
Girl girl =new Girl("mm");
boy.setGirl(girl);
System.out.println(boy);
Boy boy2= (Boy) boy.clone();
System.out.println(boy2);
boy2.getGirl().name="dmm";
System.out.println(boy2);
System.out.println(boy);
}
}
class Boy implements Cloneable{
String name;
Girl girl;
public Boy(String name) {
this.name = name;
}
public Girl getGirl() {
return girl;
}
public void setGirl(Girl girl) {
this.girl = girl;
}
@Override
public String toString() {
return "Boy{" +
"name='" + name + '\'' +
", girl=" + girl +
'}';
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
- 浅克隆结果
public class Test09013Object2 {
public static void main(String[] args) throws CloneNotSupportedException {
Boy2 boy =new Boy2("小明");
Girl2 girl =new Girl2("mm");
boy.setGirl(girl);
System.out.println(boy);
Boy2 boy2= (Boy2) boy.clone();
System.out.println(boy2);
boy2.getGirl().name="dmm";
System.out.println(boy2);
System.out.println(boy);
}
}
class Boy2 implements Cloneable{
String name;
Girl2 girl;
public Boy2(String name) {
this.name = name;
}
public Girl2 getGirl() {
return girl;
}
public void setGirl(Girl2 girl) {
this.girl = girl;
}
@Override
public String toString() {
return "Boy{" +
"name='" + name + '\'' +
", girl=" + girl +
'}';
}
@Override
protected Object clone() throws CloneNotSupportedException {
Boy2 boy= (Boy2) super.clone();
Girl2 girl2= (Girl2) girl.clone();
boy.setGirl(girl2);
return boy;
}
}
class Girl2 implements Cloneable{
String name;
public Girl2(String name) {
this.name = name;
}
@Override
public String toString() {
return "Girl{" +
"name='" + name + '\'' +
'}';
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
- 深克隆结果