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呢。
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呢。
解决方案 »
- 很重要的一个问题,忘不吝推荐
- 大家帮我看看Eclipse插件打包的问题
- Exception in thread "main" java.lang.NullPointerException at A.main(A.java:8)
- 请教论坛各位大虾,如何将一个字符串加密成Long类型的数据?最好是用DES加密~~谢了
- java beans sql 查询 (设计思想与功能,哪个更重要!)
- 为什么进入程序员的门槛会如此艰难?(4)
- 处学java,推荐基本书和网站
- jbuilder恢复以前的版本,怎样加入history,怎样恢复到某一版本?
- 调用函数出错,请各位指点,谢谢!!!!!
- 为什么?这是为什么?
- java 里的同步关键字 也太长了吧syncXXX 我又忘记了,为什么不搞个像c#那样的lock 啊 。
- 面试的问题,大家进来看一下
e1.s = new Student("solog");只是指向另一个对象
而e2.s仍然指向new Student("leon")这个对象
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了