1. 程式人生 > >java對象的深淺克隆

java對象的深淺克隆

support port void AC info tao alt 進行 HR

package CloneTest;

class Dog implements Cloneable{
private String dname;
private Integer dage;
public Dog clone() throws CloneNotSupportedException{
Dog cloned=(Dog) super.clone();
return cloned;

}

public String getDname() {
return dname;
}

public void setDname(String dname) {
this.dname = dname;
}

public Integer getDage() {
return dage;
}

public void setDage(Integer dage) {
this.dage = dage;
}

@Override
public String toString() {
return "Dog [dname=" + dname + ", dage=" + dage + "]";
}

public Dog(String dname, Integer dage) {
super();
this.dname = dname;
this.dage = dage;
}

}

class Person implements Cloneable {
private String name;
private Integer age;
private Dog dog;

public Person(String name, Integer age, Dog dog) {
this.name = name;
this.age = age;
this.dog = dog;
}

public Person clone() throws CloneNotSupportedException {
Person cloned = (Person) super.clone();
return cloned;

}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", dog=" + dog + "]";
}

public Dog getDog() {
return dog;
}

public void setDog(Dog dog) {
this.dog = dog;
}

}

public class CloneTest {
public static void main(String[] args) throws CloneNotSupportedException {
Dog dog1 = new Dog("楊狗", 5);
Person p1 = new Person("wantao", 20, dog1);
System.out.println("原對象" + p1.getName() + "他的狗為"
+ p1.getDog().getDname());
System.out.println("第一次進行克隆:");
Person p2 = p1.clone();
System.out.println("克隆對象" + p2.getName() + "克隆狗為"
+ p2.getDog().getDname());
System.out.println(p1 == p2 ? "克隆對象與原對象為同一個對象" : "克隆對象與原對象為不同對象");
System.out.println(p1.getDog() == p2.getDog() ? "克隆對象的狗與原對象的狗為同一只狗"
: "克隆對象的狗與原對象的狗為不同的狗");
System.out.println("第二次進行克隆");
Person p3=p1.clone();
p3.setDog(p1.getDog().clone());
System.out.println("克隆對象" + p3.getName() + "克隆狗為"
+ p3.getDog().getDname());
System.out.println(p1 == p3 ? "克隆對象與原對象為同一個對象" : "克隆對象與原對象為不同對象");
System.out.println(p1.getDog() == p3.getDog() ? "克隆對象的狗與原對象的狗為同一只狗"
: "克隆對象的狗與原對象的狗為不同的狗");

}

}

技術分享圖片

技術分享圖片

java對象的深淺克隆