演示 Java 中的 clone() 方法
java 8object oriented programmingprogramming
可以使用 Java 中的 clone() 方法克隆对象。被克隆对象的类应实现接口 java.lang.Cloneable,否则使用 clone() 方法时会抛出异常 CloneNotSupportedException。
下面给出了一个演示 Java 中的 clone() 方法的程序:
示例
class CloneClass implements Cloneable { int x; char y; CloneClass cloneFunc() { try { return (CloneClass) super.clone(); } catch (CloneNotSupportedException e) { System.out.println("Cloning cannot be done"); return this; } } } public class Demo { public static void main(String args[]) { CloneClass obj1 = new CloneClass(); CloneClass obj2; obj1.x = 8; obj1.y = 'A'; obj2 = obj1.cloneFunc(); System.out.println("For object obj1"); System.out.println("obj1.x = " + obj1.x); System.out.println("obj1.y = " + obj1.y); System.out.println("
For object obj2"); System.out.println("obj2.x = " + obj2.x); System.out.println("obj2.y = " + obj2.y); } }
输出
For object obj1 obj1.x = 8 obj1.y = A For object obj2 obj2.x = 8 obj2.y = A