关于clone困惑了!

malong_01223 2008-03-28 03:57:30
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呢。
...全文
48 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
kevinchj 2008-03-28
  • 打赏
  • 举报
回复
看错了……实在不好意思……
楼上满分!
还有疑问继续问。
吴冬冬 2008-03-28
  • 打赏
  • 举报
回复

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了
吴冬冬 2008-03-28
  • 打赏
  • 举报
回复
因为e2克隆的只是new Student("leon")的引用
e1.s = new Student("solog");只是指向另一个对象
而e2.s仍然指向new Student("leon")这个对象
kevinchj 2008-03-28
  • 打赏
  • 举报
回复
那就不是浅拷贝了……
是深拷贝了

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧