PrototypeClass.java
public class PrototypeClass implements Cloneable {@Overridepublic PrototypeClass clone() {try {final PrototypeClass instance = (PrototypeClass) super.clone();return instance;} catch (CloneNotSupportedException e) {return null;}}
}
1、构造函数不会被执行
public class Thing implements Cloneable {public Thing() {System.out.println("构造函数被执行了...");}@Overridepublic Thing clone() {try {Thing instance = (Thing) super.clone();return instance;} catch (CloneNotSupportedException e) {return null;}}public static void main(String[] args) {// 新建一个对象.Thing thing = new Thing();// clone 一个对象.Thing cloned = thing.clone();}
}
2、浅拷贝和深拷贝
浅拷贝
public class Thing implements Cloneable {private List<String> list = new ArrayList<>();@Overridepublic Thing clone() {try {Thing instance = (Thing) super.clone();return instance;} catch (CloneNotSupportedException e) {return null;}}public void add(final String value) {this.list.add(value);}public List<String> getList() {return list;}public static void main(String[] args) {// 新建一个对象.Thing thing = new Thing();thing.add("张三");// clone 一个对象.Thing cloned = thing.clone();cloned.add("李四");System.out.println(thing.getList());}
}
[张三, 李四]
深拷贝
public class Thing implements Cloneable {private ArrayList<String> list = new ArrayList<>();@Overridepublic Thing clone() {try {Thing instance = (Thing) super.clone();instance.list = (ArrayList<String>)this.list.clone();return instance;} catch (CloneNotSupportedException e) {return null;}}public void add(final String value) {this.list.add(value);}public List<String> getList() {return list;}public static void main(String[] args) {// 新建一个对象.Thing thing = new Thing();thing.add("张三");// clone 一个对象.Thing cloned = thing.clone();cloned.add("李四");System.out.println(thing.getList());}
}
[张三]