/**
* 测试自定义clone()方法
* @author
* wavesun(wavesun@live.cn)
*/
public class Location implements Cloneable
{
private int x;
private int y;
public Location(int x,int y){
this.x=x;
this.y=y;
}
public void setLocation(int x,int y){
this.x=x;
this.y=y;
}
public Location clone(){
Location l=null;
try{
System.out.println(super.toString());
l=(Location)super.clone();
}catch(CloneNotSupportedException e){
throw new RuntimeException("not implements Cloneable");
}finally{
return l;
}
}
public String toString(){
return ""+x+","+y;
}
public static void main(String args[]){
Location lOne=new Location(5,6);
Location lTwo=lOne.clone();
lOne.x=7;
lOne.y=9;
//可以看到clone()方法正确执行
System.out.println("("+lOne.toString()+"),("+lTwo.toString()+")");
}
}
网上找了下,原来是这样的。
下边贴出的是解释,出自
http://old.blog.edu.cn/user1/5010/archives/2004/17457.shtml为什么调用Object的clone方法却可以使得自己类中的对象被clone呢?Object中的clone执行的时候使用了RTTI(run-time type identification)的机制,动态得找到目前正在调用clone方法的那个reference,根据它的大小申请内存空间,然后进行bitwise的复制,将该对象的内存空间完全复制到新的空间中去,从而达到shallowcopy的目的。
本文通过一个Java示例,展示了如何实现Cloneable接口并重写clone()方法来完成对象的浅拷贝。深入探讨了Object类中的clone方法如何利用RTTI机制实现对象的复制。

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



