Test深度复制

来源:互联网 发布:centos6 yum php7 编辑:程序博客网 时间:2024/04/30 16:15

package Test深度复制;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


class Teacher implements Cloneable,java.io.Serializable//实现接口
{
 String name;
 int age;
 
 public Teacher(String name,int age)
 {
  this.name=name;
  this.age=age;
  
 }
 
 public Object clone()
 {
  Teacher ter=null;
  try {
   ter=(Teacher)super.clone();
  } catch (CloneNotSupportedException e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
  }
  return ter;
 }
}
class Student implements Cloneable,java.io.Serializable//实现接口
{
 String name;
 int age;
 Teacher t;
 public Student(String name,int age,Teacher t)
 {
  this.name=name;
  this.age=age;
  this.t=t;
 }
 public Object clone()
 {
  Student str=null;
  
  try {
   str=(Student)super.clone();
   
  } catch (CloneNotSupportedException e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
  }
  //为什么会产生不可视的错误呢,原因是clone在Object中是private修饰的,在其它的子类中,
  //我们知道,任何一个类都是Object的子类,不能直接访问这个clone方法的.现在我们再回头看上面teacher
  //类中的clone方法中是用的super.clone();也只有这样才能引用。
  //有的同学可能会想那我们为什么不在一行的代码中也用super呢,例如使用呵呵,可能是我想多了,
  //我还真不知道该怎么样去写,如果用super的话,那我们想复制的是什么呢,只是当前的类student,而类的
  //teacher类还是复制不到,所以也就用了上面的teacher类重载clone方法了。
  str.t=(Teacher)t.clone();
  return str;
 }
 
 public Object deepClone() throws IOException, ClassNotFoundException
 {
  ByteArrayOutputStream bo=new ByteArrayOutputStream();
  ObjectOutputStream oo=new ObjectOutputStream(bo);
  oo.writeObject(this);
  ByteArrayInputStream bi=new ByteArrayInputStream(bo.toByteArray());
  ObjectInputStream oi=new ObjectInputStream(bi);
  return(oi.readObject());
  
 }
 public static void main(String[] args) throws IOException, ClassNotFoundException{
  Teacher t=new Teacher("wang teacher",40);
  Student s1,s2 = null;
  s1=new Student("zhang san",20,t);
  //s2=(Student)s1.clone();
  s2=(Student)s1.deepClone();
  s2.name="wangwu";
  s2.age=22;
  s2.t.name="li teacher";
  if(s1==s2){
   
   System.out.println("yes the same instace");
  }
  System.out.println(s1.name+","+s1.age+","+s1.t.name);
  
  
 }
}

原创粉丝点击