Deap Clone

来源:互联网 发布:逻辑回归算法流程 编辑:程序博客网 时间:2024/05/16 15:48

 package others;

class c1 implements Cloneable {

 c2 c2;

 String b;

 String c;

 public c1(String b, String c, c2 c2) {
  this.b = b;
  this.c = c;
  this.c2 = c2;
 }

 public Object clone() {
  c1 o = null;
  try {
   o = (c1) super.clone();
  } catch (CloneNotSupportedException e) {
   e.printStackTrace();
  }
  o.c2 = (c2) c2.clone();
  return o;
 }

}

class c2 implements Cloneable {

 String a;

 public c2(String a) {
  this.a = a;
 }

 public Object clone() {
  try {
   return (c2) super.clone();
  } catch (CloneNotSupportedException e) {
   e.printStackTrace();
   return null;
  }
 }

}

public class DeapClone {

 public static void main(String[] args) {
  c2 c2 = new c2("2");
  c1 c1 = new c1("a", "b", c2);
  c1 c11 = (c1) c1.clone();
  c11.c2.a = "changed";
  //改变c11中c2,c1里的c2并未改变。如果c2未实现clone方法,则c1里的c2并未改变将改变
  //对象中的对象必须实现clone,值则不用
  System.out.println(c1.c2.a);
 }

}

原创粉丝点击