计算机二级

3773考试网计算机等级考试计算机二级正文

java中类的拷贝

来源:fjzsksw.com 2010-4-1 14:26:12

 

 return obj ;

  }

  }

  在该类中也会继承Cloneable接口,并且重写Clone方法,因为在Student类中会引用到teacher类,那么在clone Student类时,传递的是teacher类的引用,因此我们在Student类中显示的指定对其中的teacher对象进行clone,否则 clone 的是teacher对象的引用,对clone后的对象进行操作,也会影响到源对象的。

  看客户端:

  package clonedemo;

  public class client ...{

  /** *//**

  * @param args

  */

  public static void main(String[] args) ...{

  // TODO Auto-generated method stu

  teacher tea = new teacher("hello",66) ;

  Student stu1 = new Student("jacky",33,tea) ;

  Student stu2 = (Student)stu1.clone() ;

  stu2.showInfo("stu2") ;

  System.out.println("-------------------") ;

  stu2.getTea().setName("world") ;

  stu2.getTea().setAge(88) ;

  stu1.showInfo("stu1") ;

  //System.out.println("-------------------") ;

  //stu2.showInfo("stu2") ;

  }

  }

  若对stu2进行更改后,stu1中的属性并没有改变,这就是深拷贝后的结果。\

 

 

 

上一页  [1] [2] [3] [4] 

触屏版 电脑版
3773考试网 琼ICP备12003406号-1