Easy Solution to implement clone java object

来源:互联网 发布:yum安装软件原理 编辑:程序博客网 时间:2024/05/16 05:21

The easiest solution to this is to make the base class "implements Cloneable" and have the base class and all sub-classes contain the clone() method. When a class has data in it that must be cloned, adding a line or two to the clone() method is straightforward.

Example:

abstract public class X implements Cloneable {        public X clone() throws CloneNotSupportedException {                return (X) super.clone();        }} abstract public class Y extends X {        public Y clone() throws CloneNotSupportedException {                return (Y) super.clone();        }} public class Z extends Y {        public Z clone() throws CloneNotSupportedException {                return (Z) super.clone();        }} public class test1 {        public void function() throws CloneNotSupportedException {                Y varY1 = new Z();                Y varY2 = varY1.clone();        }}


From:http://en.wikipedia.org/wiki/Clone_(Java_method)