为了获取对象的一份拷贝,我们可以利用Object类的clone()方法。
在派生类中覆盖基类的clone()方法,并声明为public。
在派生类的clone()方法中,调用super.clone()。
在派生类中实现Cloneable接口。
为什么我们在派生类中覆盖Object的clone()方法时,一定要调用super.clone()呢?在运行时刻,Object中的clone()识别出你要复制的是哪一个对象,然后为此对象分配空间,并进行对象的复制,将原始对象的内容一一复制到新对象的存储空间中。
Student s1 = new Student("gaoer", 14);
System.out.println("s1name=" + s1.getName());
Student s2 = s1; // 未使用clone,他俩使用一个地址,
s2.setAge(12);
s2.setName("zhangsan");
System.out.println("s1name=" + s1.getName());
Student s3 = (Student) s1.clone();
s3.setAge(12);
s3.setName("lisi");
System.out.println("s1name=" + s1.getName());
package l4;
/**
*
* @author Administrator
* 当没有引用类型的变量时,为浅层次的拷贝
*
*/
public class Student implements Cloneable {
private String name;
private int age;
public Student(String name, int age) {
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;
}
protected Object clone() throws CloneNotSupportedException {
Object o = null;
o = super.clone();
return o;
}
}
package l4;
/**
*
* @author Administrator
* 当没有引用类型的变量时,为浅层次的克隆
* 当有引用类型的变量时,为深层次的克隆
*/
public class Student implements Cloneable {
private String name;
private int age;
Point pt;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student(String name, int age,Point pt) {
this.name = name;
this.age = age;
this.pt = pt;
}
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;
}
protected Object clone() throws CloneNotSupportedException {
Student o = null;
o = (Student)super.clone();
o.pt = (Point)pt.clone();
return o;
}
}
package l4;
public class Point implements Cloneable {
public int x;
public int y;
@Override
public String toString() {
return "x=" + x + "y=" + y;
}
protected Object clone() throws CloneNotSupportedException {
Object o = null;
o = super.clone();
return o;
}
}
posted on 2011-01-04 22:16
冯占科 阅读(160)
评论(0) 编辑 收藏