class Student {
public String name ;
public Student (String name ){
this.name =name;
}
}
class Employee implements Cloneable{
public String str = new String("welcome");
public int i = 0;
public Student s = null;
public Object clone(){
Object clone=null;
try{
clone = super.clone();
}catch(Exception e){
e.printStackTrace();
}
return clone;
}
}
public class Test { public static void main(String[] args) {
// TODO Auto-generated method stub
Employee e1 = new Employee();
e1.s = new Student("leon");
Employee e2 = (Employee)e1.clone();
System.out.println(e1.str);
System.out.println(e1.i);
System.out.println(e2.str);
System.out.println(e2.i);
System.out.println(e2.s.name);
e1.str = "hello";
e1.i = 2;
e1.s = new Student("solog");
System.out.println("--------------------");
System.out.println(e1.str);
System.out.println(e1.i);
System.out.println(e2.str);
System.out.println(e2.i);
System.out.println(e2.s.name);//注释a
}}
这样不是浅克隆么?按理说 注释a 那一段应该变化为solog,为什么还是leon呢。

解决方案 »

  1.   

    因为e2克隆的只是new Student("leon")的引用
    e1.s = new Student("solog");只是指向另一个对象
    而e2.s仍然指向new Student("leon")这个对象
      

  2.   


    Employee e1 = new Employee();
            e1.s = new Student("leon");
            Employee e2 = (Employee)e1.clone();
            System.out.println(e1.str);
            System.out.println(e1.i);
            System.out.println(e2.str);
            System.out.println(e2.i);
            System.out.println(e2.s.name);
            e1.str = "hello";
            e1.i = 2;
            //e1.s = new Student("solog");
            e1.s.name="solog";
            System.out.println("--------------------");
            System.out.println(e1.str);
            System.out.println(e1.i);
            System.out.println(e2.str);
            System.out.println(e2.i);
            System.out.println(e2.s.name);//注释a这样的结果e2.a.name就是solog了