如果我们尝试对未实现 cloneable 接口的类的对象调用 clone() 方法,我们将收到 clonenotsupportedexception 。该接口是一个标记接口,该接口的实现仅表明可以在实现类的对象上调用object.clone()方法。
语法protected object clone() throws clonenotsupportedexception
我们可以通过两种方式实现clone()方法
浅复制这是object.clone()提供的默认克隆功能的结果 方法(如果类也有非基本数据类型成员)。在浅复制的情况下,克隆对象还引用原始对象所引用的同一对象,因为仅复制对象引用,而不复制引用的对象。
示例public class shallowcopytest { public static void main(string args[]) { a a1 = new a(); a a2 = (a) a1.clone(); a1.sb.append("tutorialspoint!"); 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; }}
输出welcome to tutorialspoint!welcome to tutorialspoint!
深度复制我们需要为非基本类型的类重写clone()方法成员来实现深度复制,因为它还需要克隆成员对象,而默认克隆机制不会这样做。
示例public class deepcopytest { public static void main(string args[]) { a a1 = new a(); a a2 = (a) a1.clone(); a1.sb.append(" tutorialspoint!"); 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; }}
输出welcome to tutorialspoint!welcome to
以上就是在java中,clone()方法的重要性是什么?的详细内容。