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

来源:互联网 发布:数据来源英文 编辑:程序博客网 时间:2024/04/27 20:29
/**
* 测试自定义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

0 0
原创粉丝点击