zoukankan      html  css  js  c++  java
  • 谨慎的覆盖clone()方法

    如果一个类实现了Cloneable方法,就可以调用clone方法,并且返回该对象的逐域拷贝,否则抛出cloneNotSupportedException异常。

    下面是一个演示clone方法的类,注意深度拷贝问题:


    public class testClone implements Cloneable{
    inClass in;
    public static void main(String[] args) throws CloneNotSupportedException {
       testClone t1=new testClone();
       t1.in=new inClass();
       t1.in.t=10;
       t1.in.tag="obeject1";
       testClone t2=(testClone) t1.clone();
       System.out.println(t1);
       System.out.println(t2);
       t2.in.tag="change";
       System.out.println(t1);
       System.out.println(t2);
    }
    @Override public String toString(){
       return in.tag+" "+in.t;
    }

    @Override public testClone clone(){

       try {
        return (testClone) super.clone();
       } catch (CloneNotSupportedException e) {
        throw new AssertionError();
       }
    }

    }
    class inClass{
    String tag;
    int t;
    }
    输出结果为:

    obeject1 10
    obeject1 10
    change 10
    change 10

  • 相关阅读:
    特性标签的灵活使用
    算法实例题
    网络抓包工具
    vs2010
    .NET Remoting vs Web Service
    电子商务网站设计学习
    EXCEL导出
    C# 16进制与字符串、字节数组之间的转换
    DES加密
    DataGridView生成CSV,XML 和 EXCEL文件
  • 原文地址:https://www.cnblogs.com/macula7/p/1960611.html
Copyright © 2011-2022 走看看