复制代码
- //:DeepCopy.java
- //Cloningacomposedobject
- classDepthReadingimplementsCloneable{
- privatedoubledepth;
- publicDepthReading(doubledepth){
- this.depth=depth;
- }
- publicObjectclone(){
- Objecto=null;
- try{
- o=super.clone();
- }catch(CloneNotSupportedExceptione){
- e.printStackTrace();
- }
- returno;
- }
- }
- classTemperatureReadingimplementsCloneable{
- privatelongtime;
- privatedoubletemperature;
- publicTemperatureReading(doubletemperature){
- time=System.currentTimeMillis();
- this.temperature=temperature;
- }
- publicObjectclone(){
- Objecto=null;
- try{
- o=super.clone();
- }catch(CloneNotSupportedExceptione){
- e.printStackTrace();
- }
- returno;
- }
- }
- classOceanReadingimplementsCloneable{
- privateDepthReadingdepth;
- privateTemperatureReadingtemperature;
- publicOceanReading(doubletdata,doubleddata){
- temperature=newTemperatureReading(tdata);
- depth=newDepthReading(ddata);
- }
- publicObjectclone(){
- OceanReadingo=null;
- try{
- o=(OceanReading)super.clone();
- }catch(CloneNotSupportedExceptione){
- e.printStackTrace();
- }
- //Mustclonehandles:
- o.depth=(DepthReading)o.depth.clone();
- o.temperature=
- (TemperatureReading)o.temperature.clone();
- returno;//UpcastsbacktoObject
- }
- }
- publicclassDeepCopy{
- publicstaticvoidmain(String[]args){
- OceanReadingreading=
- newOceanReading(33.9,100.5);
- //Nowcloneit:
- OceanReadingr=
- (OceanReading)reading.clone();
- }
- }///:~
欢迎光临 仓酷云 (http://ckuyun.com/) | Powered by Discuz! X3.2 |