使用和不使用 Cloneable 覆盖克隆
我已经阅读了 Object
和 Cloneable
的 javadoc,但我只是没有“得到”一些东西。有人可以向我解释一下以下两个示例的性能和/或功能差异:
public class Widget
{
@Override
public Widget clone()
{
// ... return a clone of this Widget
}
}
..and:
public class Widget implements Cloneable
{
@Override
public Widget clone()
{
// ... return a clone of this Widget
}
}
由于 Cloneable
没有任何与之关联的方法,并且只允许您访问 对象的受保护的clone()方法,一开始实现它是否有意义,因为你最终必须以任何方式编写自己的(安全)clone()代码?预先感谢您的任何澄清/意见。
I've read the javadoc for both Object
and Cloneable
and am just not "getting" something. Can someone please explain to me the performance and/or functional differences to the two following examples:
public class Widget
{
@Override
public Widget clone()
{
// ... return a clone of this Widget
}
}
..and:
public class Widget implements Cloneable
{
@Override
public Widget clone()
{
// ... return a clone of this Widget
}
}
Since Cloneable
does not have any methods tied to it, and only gives you access to Object
's protected clone() method, does it ever make sense to even implement it in the first place, seeing that you're going to have to end up writing your own (safe) clone() code any way? Thanks in advance for any clarification/input.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是合同义务。
虽然可能没有可以重写的方法,但您仍然在实现您所属的接口。在此过程中,您将承担后续合同带来的所有内容。它迫使您有意识地实现
clone()
方法,从而使行为变得明确。It's a contractual obligation.
While there may be no methods to override, you are still implementing an interface you are part of. In doing this you take on all that comes with its subsequent contract. It forces you to knowingly implement the
clone()
method thus making the behavior explicit.a) 克隆调用构造对象的语言外方式 - 无需构造函数。
b) 克隆要求您以某种方式处理 CloneNotSupportedException - 或者打扰客户端代码来处理它。
c) 好处很小——您只是不必手动编写复制构造函数。
因此,请谨慎使用 Cloneable。与你为做好事而需要付出的努力相比,它并没有给你带来足够的好处。
关于 Java 可克隆
a) Cloning invokes extralinguistic way of constructing objects - without constructors.
b) Cloning requires you to treat somehow with CloneNotSupportedException - or to bother client code for treating it.
c) Benefits are small - you just don't have to write manually a copying constructor.
So, use Cloneable judiosly. It doesn't give you suffisient benefits in compare with effort you need to apply to do all right.
About Java cloneable