如果超类已经完成了clone()方法,子类是否需要显式地重写clone()方法?

发布于 2024-09-28 03:15:01 字数 206 浏览 0 评论 0原文

如果类A扩展了类B并且类B已经实现了Cloneable接口,那么类A是否有必要> 声明“clone() throws CloneNotSupportedException”?

我想这不应该是强制性的,因为克隆 A 类对象的属性将自动从 B 类继承。

If class A extends class B and class B has already implemented the Cloneable interface, then is it necessary for class A to declare 'clone() throws CloneNotSupportedException'?

I guess it should not be mandatory, as the property to clone objects of class A would automatically be inherited from class B.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

情仇皆在手 2024-10-05 03:15:01

如果类 B 定义了非原始可变成员字段,则有必要重写 clone()。这些需要在 B.clone() 中显式深度复制。如果 B 仅包含原始和/或不可变数据成员,则 A.clone() 将完成这项工作。

有关更详细的说明,请参阅我之前的回答类似的问题。

It is necessary to override clone() if class B defines non-primitve mutable member fields. These need to be deep copied explicitly within B.clone(). If B only contains primitive and/or immutable data members, A.clone() will do the job.

For a more detailed explanation, see this earlier answer of mine to a similar question.

青衫负雪 2024-10-05 03:15:01

如果父类和所有祖先类通过调用其父类的 Clone 方法来实现其 Clone 方法,一直到 Object.clone >,如果子类添加的任何字段都没有保留对一个对象上应该可以更改而不影响另一个对象的事物的引用,那么可以简单地继承clone而不覆盖它。如果父类实现了上述的clone方法,但子类添加了自己需要克隆的字段,那么最好的模式是子类调用base.Clone,然后克隆相应的字段。

如果父类或任何祖先没有如上所述实现其 Clone 方法,而是使用复制构造函数,则派生类以及从其派生的所有基类)必须重写 Clone< /code> 执行同样的操作,无论基类是否添加任何新字段。

不幸的是,我不知道有什么好方法来确定父类属于哪个类别。如果父类通过调用base.Clone来支持Clone,那么派生类通过实现复制构造函数不必要地破坏链将是不幸的。另一方面,如果父类将 Clone 实现为复制构造函数,则不这样做的基类将具有损坏的语义。

If the parent class, and all ancestors, implements its Clone method by calling its parent class' Clone method, all the way up to Object.clone, and if none of the fields added by the subclass hold references to things which should be changeable on one object without affecting the other, then one can simply inherit clone without overriding it. If the parent class implements the clone method as described above but the subclass adds fields that themselves need to be cloned, the best pattern is for the subclass to call base.Clone and then clone the appropriate fields.

If the parent class or any ancestor does not implement its Clone method as described above but instead uses a copy constructor, then the derived class, and all base classes derived from it) must override Clone to do likewise, regardless of whether the base class adds any new fields.

Unfortunately, I know of no nice way to ascertain which category a parent class belongs to. If a parent class supports Clone by calling base.Clone, it would be unfortunate for a derived class to needlessly break the chain by implementing a copy constructor. On the other hand, if the parent class implements Clone as a copy constructor, a base class which does not do so will have broken semantics.

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