
// 具体原型类: 奖状
public class Citation implements Cloneable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show() {
System.out.println("三好学生:" + name);
}
@Override
protected Citation clone() throws CloneNotSupportedException {
return (Citation) super.clone();
}
}
// 访问类
public class CitationTest {
public static void main(String[] args) throws CloneNotSupportedException {
Citation c1 = new Citation();
c1.setName("张三");
Citation c2 = c1.clone();
c2.setName("李四");
c1.show();
c2.show();
}
}
/* 输出结果:
三好学生:张三
三好学生:李四
*/
// 学生类
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// 具体原型类: 奖状
public class Citation implements Cloneable {
private Student student;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public void show() {
System.out.println("三好学生:" + student.getName());
}
@Override
protected Citation clone() throws CloneNotSupportedException {
return (Citation) super.clone();
}
}
// 访问类
public class CitationTest {
public static void main(String[] args) throws CloneNotSupportedException {
Citation c1 = new Citation();
Student student1 = new Student();
student1.setName("张三");
c1.setStudent(student1);
Citation c2 = c1.clone();
Student student2 = c2.getStudent();
student2.setName("李四");
System.out.println("student1和student2是同一个对象吗?" + (student1 == student2));
c1.show();
c2.show();
}
}
/* 输出结果:
student1和student2是同一个对象吗?true
三好学生:李四
三好学生:李四
*/
// 学生类
public class Student implements Serializable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// 具体原型类: 奖状
public class Citation implements Cloneable, Serializable {
private Student student;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public void show() {
System.out.println("三好学生:" + student.getName());
}
@Override
protected Citation clone() throws CloneNotSupportedException {
return (Citation) super.clone();
}
}
// 访问类
public class CitationTest {
public static void main(String[] args) throws Exception {
Citation c1 = new Citation();
Student student1 = new Student();
student1.setName("张三");
c1.setStudent(student1);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\study\\a.txt"));
oos.writeObject(c1);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\study\\a.txt"));
Citation c2 = (Citation) ois.readObject();
ois.close();
Student student2 = c2.getStudent();
student2.setName("李四");
System.out.println("student1和student2是同一个对象吗?" + (student1 == student2));
c1.show();
c2.show();
}
}
/* 输出结果:
student1和student2是同一个对象吗?false
三好学生:张三
三好学生:李四
*/