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() ? "克隆对象的狗与原对象的狗为同一只狗"
: "克隆对象的狗与原对象的狗为不同的狗");
}
}
原文地址:https://www.cnblogs.com/wantao/p/8543863.html