java拷贝构造函数_java-复制构造函数vs可克隆.我为什么不考虑...

我正在阅读answer,他提到了link,作者在其中解释了为什么我们不应该使用Cloneable.但是,仍然怀疑那里所说的是什么

If I have an array of Cloneable, you would think that I could run down

that array and clone every element to make a deep copy of the array,

but I can’t. You can not cast something to Cloneable and call the clone

method, because Cloneable doesn’t have a public clone method and

neither does Object. If you try to cast to Cloneable and call the

clone method, the compiler will say you are trying to call the

protected clone method on object.

但是,我在这里做了

Init s = Init.getInstance(); // getting instance

int count=0;

Cloneable[] v = new Cloneable[5]; // creating array

Init x = s;

Init y = new Init(s);

try {

while (count < 5) {

v[count++] = (Cloneable) s.clone(); // casting it.

}

s.setClassName("Example");

System.out.println(((Init) v[2]).getClassName()); // Displaying.

} catch (CloneNotSupportedException ex) {

ex.printStackTrace();

}

我能够创建Cloneable数组,我做了作者所说的会导致错误的操作,还是我误解了作者的声明?任何人,请帮助我了解选择“复制构造函数”而不是“可复制”的原因.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值