super.clone()调用的是哪个对象?

本文介绍了一个简单的Java类实现Cloneable接口并重写clone方法的例子。通过实例演示了如何使用super.clone方法完成对象的浅复制,并展示了克隆前后对象状态的变化。
/**
* 测试自定义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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值