Java:有关克隆方法的问题
我正在阅读《Effective Java》,书中对克隆方法有以下评论。
在实践中, 实现 Cloneable 的类应该提供正确的 有效的公共克隆方法。 一般来说,不可能这样做,除非 该类的所有超类都提供了良好的克隆实现, 无论是公开的还是受保护的。
任何人都可以举例说明为什么不能这样做吗?
I am reading Effective Java and the book has the below comment on the clone method.
In practice,
a class that implements Cloneable is expected to provide a properly
functioning public clone method. It is not, in general, possible to do so unless
all of the class’s superclasses provide a well-behaved clone implementation,
whether public or protected.
Can anyone give examples of why this can't be done ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
想象一下,其中一个基类有一个私有字段,可以以特定方式复制该字段,以使“克隆”在语义上有效。
如果该基类没有提供正确的克隆实现,则派生类也不能提供 - 它无法正确构建该私有字段。
Imagine one of the base classes has a private field that to be copied in a specific way for a "clone" to be semantically valid.
If that base class does not provide a correct clone implementation, the derived class can't either - it has no way of building that private field correctly.
基本上,如果类层次结构的一部分包含不受您控制且不属于 JDK 一部分的类(即第 3 方闭源类),并且该类未实现行为良好的克隆( ) 方法,那么生成它就不会特别容易。
Basically, if part of your class hierarchy includes a class that is not under your control and not part of the JDK (ie. a 3rd party closed-source class), and this class does not implement a well-behaved
clone()
method, then it's not going to be particularly easy to produce one.在许多情况下,一个类通常是在编写时没有实现克隆。因此,当编写子类时,它同样是在未实现克隆的情况下编写的。在某些时候,需要在子类中编写克隆方法,但它的父类没有。
In many cases a class is usually written with clone not implemented. So when a child class is written it is likewise written with clone not implmented. At some point it is required to write a clone method in a child class but it's parents don't have one.
这可以是答案吗?
this can be the anwser?