class Teacher{
   String name;
   int age;
   Teacher(String name,int age){
       this.name=name;
       this.age=age;
   }
}
class Student implements Cloneable{
   String name;
   int age;
   Teacher t;//学生1和学生2的引用值都是一样的。
   Student(String name,int age,Teacher t){
       this.name=name;
       this.age=age;
       this.t=t;
   }
   public Object clone(){
       Student stu=null;
       try
           stu=(Student)super.clone();
       }catch(CloneNotSupportedException e)
           e.printStackTrace();
       }
       stu.t=(Teacher)t.clone();
       return stu;
   }
   public static void main(String[] args){F%7#d
       Teacher t=new Teacher("tangliang",30);
       Student s1=new Student("zhangsan",18,t);
       Student s2=(Student)s1.clone();
       s2.t.name="tony";
       s2.t.age=40;
       System.out.println("name="+s1.t.name+","+"age="+s1.t.age);
}
         //学生1的老师成为tony,age为40。C9."
   }
}
实现修改s2 s1 的老师不会改变

解决方案 »

  1.   

    你的techer类没有实现克隆方法,所以stu.t=(Teacher)t.clone();不一定有效。class Student implements Cloneable{
      String name;
      int age;
      Teacher t;//学生1和学生2的引用值都是一样的。
      Student(String name,int age,Teacher t){
      this.name=name;
      this.age=age;
      this.t=t;
      }
      public Object clone(){
      Student stu=null;
      try
      stu=(Student)super.clone();
      }catch(CloneNotSupportedException e)
      e.printStackTrace();
      }
      //stu.t=(Teacher)t.clone();//修改这里
      stu.t = new Teacher(this.t.name, this.t.age);
      return stu;
      }
      

  2.   

    你想说啥呢?想复制就是要实现Cloneable接口呀
      

  3.   

    Serializable序列化 也可以实现
      

  4.   

    你Teacher又没见实现clone
    如果用重写clone需要在所有引用的类中都重写clone第二种方法使用序列化和反序列化,就不用每个类去写了
      

  5.   

    去个人 接个分 
    http://topic.csdn.net/u/20110809/19/83806c7e-c98d-43ee-ac33-8b2d9bb0bbc8.html