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

  • 相关阅读:
    Luogu3118:[USACO15JAN]Moovie Mooving
    Luogu4137:Rmq Problem/mex
    Luogu3092:[USACO13NOV]No Change
    BZOJ4321: queue2
    BZOJ4650 : [NOI2016]优秀的拆分
    webpack
    sublime eslint setup
    Sublime themes/ lint themes setup
    sublime text 3
    React
  • 原文地址:https://www.cnblogs.com/macula7/p/1960771.html
Copyright © 2011-2022 走看看