Java:clone()操作调用super.clone() [英] Java : clone() operation calling super.clone()

查看:511
本文介绍了Java:clone()操作调用super.clone()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我并不完全理解在类的clone()方法中返回super.clone()的想法。首先,与它返回一个包含LESS数据而不是请求的超类的对象有关,因为超类不是子类,而是子类是超类。如果有一个很长的子类链,每个子类都调用super.clone(),为什么不会导致它最终在链的根处调用Object.clone(),这不是任何子类? / p>

如果这令人困惑,我们深表歉意;我有时会迷惑自己

解决方案

clone()的实现code> Object 检查实际的类是否实现 Cloneable ,并创建该实际类的实例。



因此,如果你想让你的类可克隆,你必须实现 Cloneable downcast <$的结果c $ c> super.clone()到你的班级。另一个负担是对 super.clone()的调用可以抛出你必须捕获的 CloneNotSupportedException ,即使你知道它不会发生(因为你的类实现 Cloneable )。



Object 类上的可克隆接口和 clone 方法是对象的一个​​明显例子 - 导向设计出错了。


I am not fully understanding the idea of returning super.clone() in the clone() method of a class. First of all, wouldn't that relate to it returning an object that is a superclass which contains LESS data than requested, because a superclass "is not a" subclass, but a subclass "is a" superclass. And if there were a long chain of subclasses, each calling super.clone(), why wouldn't that lead to it eventually calling Object.clone() at the root of the chain, which isn't any of the subclasses?

Sorry if that was confusing; I confuse myself sometimes

解决方案

The implementation of clone() in Object checks if the actual class implements Cloneable, and creates an instance of that actual class.

So if you want to make your class cloneable, you have to implement Cloneable and downcast the result of super.clone() to your class. Another burden is that the call to super.clone() can throw a CloneNotSupportedException that you have to catch, even though you know it won't happen (since your class implements Cloneable).

The Cloneable interface and the clone method on the Object class are an obvious case of object-oriented design gone wrong.

这篇关于Java:clone()操作调用super.clone()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆