/**
* 测试自定义clone()方法
* @author
* wavesun(wavesun@live.cn)
*/
public class Test implements Cloneable
{
private int x;
private int y;
public Test(int x,int y){
this.x=x;
this.y=y;
}
public void setLocation(int x,int y){
this.x=x;
this.y=y;
}
public Test clone(){
Test l=null;
try{
System.out.println(super.toString());
l=(Test)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[]){
Test lOne=new Test(5,6);
Test lTwo=lOne.clone();
lOne.x=7;
lOne.y=9;
//可以看到clone()方法正确执行
System.out.println("("+lOne.toString()+"),("+lTwo.toString()+")");
}
* 测试自定义clone()方法
* @author
* wavesun(wavesun@live.cn)
*/
public class Test implements Cloneable
{
private int x;
private int y;
public Test(int x,int y){
this.x=x;
this.y=y;
}
public void setLocation(int x,int y){
this.x=x;
this.y=y;
}
public Test clone(){
Test l=null;
try{
System.out.println(super.toString());
l=(Test)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[]){
Test lOne=new Test(5,6);
Test lTwo=lOne.clone();
lOne.x=7;
lOne.y=9;
//可以看到clone()方法正确执行
System.out.println("("+lOne.toString()+"),("+lTwo.toString()+")");
}
}
输出结果是inner.Test@1e57e8f
(7,9),(5,6)
super.clone是克隆当前对象,调用父类方法实现浅克隆。由于返回值是object类,所以需要强制转换类型 l=(Test)super.clone();
另外实现克隆必须实现cloneable接口。
转载自:https://zhidao.baidu.com/question/937779224323079812.html
本文介绍了一个简单的Java类实现Cloneable接口并重写clone方法的例子。通过实例演示了如何使用super.clone方法完成对象的浅复制,并展示了克隆前后对象状态的变化。
569

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



