可以使用clone()
Java中的方法克隆对象。克隆其对象的类应实现java.lang.Cloneable接口,否则在clone()
使用method时会抛出CloneNotSupportedException异常。
clone()
给出了演示Java方法的程序,如下所示:
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("\nFor 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