Java:有关克隆方法的问题

发布于 2024-12-15 02:57:35 字数 222 浏览 3 评论 0原文

我正在阅读《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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

那请放手 2024-12-22 02:57:35

想象一下,其中一个基类有一个私有字段,可以以特定方式复制该字段,以使“克隆”在语义上有效。

如果该基类没有提供正确的克隆实现,则派生类也不能提供 - 它无法正确构建该私有字段。

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.

遮云壑 2024-12-22 02:57:35

基本上,如果类层次结构的一部分包含不受您控制且不属于 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.

柒夜笙歌凉 2024-12-22 02:57:35

在许多情况下,一个类通常是在编写时没有实现克隆。因此,当编写子类时,它同样是在未实现克隆的情况下编写的。在某些时候,需要在子类中编写克隆方法,但它的父类没有。

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.

烟沫凡尘 2024-12-22 02:57:35
`@override
public MyClass clone(){

Myclass clonedObj = super.clone(); // This is why the classtree all needs to be cloneable

// now copy values of all members to the new obj.
// be carefull to not copy references
clonedobj.setMyMember(this.getMyMember()); // copy of member var;
clonedobj.setMyotherMember(this.getMyOtherMember().clone()); // a composit obj must be cloned.

}
`

这可以是答案吗?

`@override
public MyClass clone(){

Myclass clonedObj = super.clone(); // This is why the classtree all needs to be cloneable

// now copy values of all members to the new obj.
// be carefull to not copy references
clonedobj.setMyMember(this.getMyMember()); // copy of member var;
clonedobj.setMyotherMember(this.getMyOtherMember().clone()); // a composit obj must be cloned.

}
`

this can be the anwser?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文