在java中,原型实现Cloneable接口实现clone接口方法。
在使用过程应该注意的一点是,Object的clone方法是不复制对象的,只会复制对象的引用,也就是说仅仅复制了对象的内存地址。所以人们常说的浅拷贝和深拷贝说的就是是否要复制对象值的操作。
代码如下:
package com.array7.prototype;
public class Run {
public static void main(String[] args) {
Prototype prototype = new Prototype();
Prototype cp = prototype.clone();
cp.run();
}
}
class Prototype implements Cloneable {
@Override
protected Prototype clone(){
Prototype prototype = null;
try {
prototype = (Prototype) super.clone();
} catch (Exception e) {
e.printStackTrace();
}
return prototype;
}
public void run() {
System.out.println("Run...");
}
}

本文详细介绍了在Java中如何通过Cloneable接口和Clone方法实现对象克隆,解释了浅拷贝和深拷贝的概念,并强调了在使用过程中需要注意的事项,避免只复制对象引用的问题。
1366

被折叠的 条评论
为什么被折叠?



