English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Theclone() The method is used to create a copy of an object of a class that it implementsCloneable interface. By default, itCopy by field Because the Object class has no knowledge of the specific class members that are called by this method on an object. Therefore, if the class only has primitive data type members, a new copy of the object will be created, and a reference to the new object copy will be returned. However, if the class contains any class type members, only references to those members' objects will be copied, so the member references in both the original object and the cloned object refer to the same object.
if an attempt is made to clone an object that has not implementedCloneable interface's class object on which the method is calledclone()method, then you will getCloneNotSupportedException . This interface ismarked interface,and that thisinterfaceThe implementation simply indicates that it can be called on objects of the implementing classObject.clone()method.
protected Object clone() throws CloneNotSupportedException
We can useclone()
Two ways to implement this method
If the class also has non-primitive data type members, then this isObject.clone()The result of the default cloning functionality provided by the method. In the case of 'shallow copy', the cloned object still refers to the same object as the original object, because only object references are copied, not the objects themselves.
public class ShallowCopyTest { public static void main(String args[]) { A a1 = new A(); A a2 = (A) a1.clone(); a1.sb.append("w3codebox!"); System.out.println(a1); System.out.println(a2); } } class A implements Cloneable { public StringBuffer sb = new StringBuffer("Welcome to "); public String toString() { return sb.toString(); } public Object clone() { try { return super.clone(); } catch(CloneNotSupportedException e) { } return null; } }
Output Result
Welcome to w3codebox! Welcome to w3codebox!
For classes with non-primitive type members, we need to overrideclone() methods to implementDeep Copy,because it also needs to clone member objects, and the default cloning mechanism cannot do this.
public class DeepCopyTest { public static void main(String args[]) { A a1 = new A(); A a2 = (A) a1.clone(); a1.sb.append(" w3codebox!"); System.out.println(a1); System.out.println(a2); } } class A implements Cloneable { public StringBuffer sb = new StringBuffer("Welcome to "); public String toString() { return sb.toString(); } public Object clone() { try { A a = (A) super.clone(); a.sb = new StringBuffer(sb.toString()); return a; } catch(CloneNotSupportedException e) { } return null; } }
Output Result
Welcome to w3codebox! Welcome to