关于java中的可克隆接口和object.clone()的困惑 [英] Confusion about cloneable interface and object.clone() in java

查看:130
本文介绍了关于java中的可克隆接口和object.clone()的困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有:

class foo implements Cloneable

然后执行:

bar = new foo();
bar.clone();

我得到一份浅层副本,无需编写任何 bar.clone() 我实现接口时通常需要做的代码。

I get a shallow copy without needing to write any bar.clone() code like I normally would need to do when I implement an interface.

我的理解是接口的函数必须由类填写实现它, Object.clone()没有实现(根据文档,类Object本身不实现Cloneable接口)

My understanding is that an interface's functions must be filled in by the class implementing it, and Object.clone() has no implementation (as per the docs, "The class Object does not itself implement the interface Cloneable")

那么我的浅层克隆来自哪里?如果 Object.clone()没有实现,那么实现 bar.clone()的代码在哪里?我很困惑。

So where does my shallow clone come from? Where is the code that implements bar.clone() if Object.clone() has no implementation? I'm confused.

推荐答案

非常小心使用克隆。事实上,我会完全避免它。我从不需要它。但是......话虽如此,我曾经读过的关于这个主题的最好的讨论是由Joshua Bloch在Effective Java中进行的。阅读第11项:明智地覆盖克隆。

Be very careful using clone. In fact, I would avoid it completely. I have never needed it. BUT... that being said, the best discussion of the topic I have ever read is by Joshua Bloch, in Effective Java. Read Item 11: "Override clone judiciously".

请自己帮忙并阅读该项目。我实际上建议阅读整章(以及本书的其余部分)。你需要知道关于克隆的一切以及我为什么要提醒你的事情。

PLEASE do yourself a favor and read that item. I actually recommend reading that entire chapter (and the rest of the book). Everything you need to know about clone and why I caution you about it is in there.

希望这有帮助。

这篇关于关于java中的可克隆接口和object.clone()的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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