/**
*演示克隆
*/
public class TestClone {
public static void main(String[] args) {
Person p1 = new Person("tom",18);
Cat c = new Cat("小明");
p1.setCat(c);
try {
Person p2 = (Person)p1.clone();
System.out.println(p2.getName()+"--"+p2.getAge());
System.out.println(p1.getCat()+"--"+p2.getCat());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
/**
*実现Cloneable接口以便克隆,该接口没有方法,是一个标记接口
*/
class Person implements Cloneable{
private String name;
private int age;
/**养了一只宠物猫*/
private Cat cat;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
/**
*深克隆
*/
public Object clone() throws CloneNotSupportedException{
//return super.clone();
Person p = (Person)super.clone();//克隆了新的人的対象
if(null!=cat){
Cat c = (Cat)cat.clone();//克隆了新的猫的対象
p.setCat(c);
}
return p;
}
}
class Cat implements Cloneable{
private String name;
public Cat(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
}
*演示克隆
*/
public class TestClone {
public static void main(String[] args) {
Person p1 = new Person("tom",18);
Cat c = new Cat("小明");
p1.setCat(c);
try {
Person p2 = (Person)p1.clone();
System.out.println(p2.getName()+"--"+p2.getAge());
System.out.println(p1.getCat()+"--"+p2.getCat());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
/**
*実现Cloneable接口以便克隆,该接口没有方法,是一个标记接口
*/
class Person implements Cloneable{
private String name;
private int age;
/**养了一只宠物猫*/
private Cat cat;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
/**
*深克隆
*/
public Object clone() throws CloneNotSupportedException{
//return super.clone();
Person p = (Person)super.clone();//克隆了新的人的対象
if(null!=cat){
Cat c = (Cat)cat.clone();//克隆了新的猫的対象
p.setCat(c);
}
return p;
}
}
class Cat implements Cloneable{
private String name;
public Cat(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
}