Effective Java:分析clone()方法 [英] Effective Java: Analysis of the clone() method

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

问题描述

请考虑以下有效Java项目11(明智地覆盖克隆),其中Josh Bloch解释了 clone()合同的错误。

Consider the following from Effective Java Item 11 (Override clone judiciously) where Josh Bloch is explaining what is wrong with the clone() contract .


此合约存在许多问题。 没有
构造函数被称为的规定过于强大。一个行为良好的克隆方法可以调用构造函数
来创建构建中的克隆内部的对象。如果类是
final,clone甚至可以返回由构造函数创建的对象。

There are a number of problems with this contract. The provision that "no constructors are called" is too strong. A well-behaved clone method can call constructors to create objects internal to the clone under construction. If the class is final, clone can even return an object created by a constructor.

有人可以解释一下Josh Bloch是什么在第一段中说如果类是 final clone 甚至可以返回由构造函数创建的对象。 final clone()有什么关系?

Can someone explain what Josh Bloch is saying in the first paragraph by "If the class is final, clone can even return an object created by a constructor." What does final have to do with clone() here?

推荐答案

如果一个类不是final,那么 clone 必须返回调用它的派生类最多的类。这不适用于构造函数,因为 clone 不知道要调用哪一个。如果一个类是final,那么它不能有任何子类,所以在克隆时调用它的构造函数没有危险。

If a class is not final, clone has to return the most derived class for which it was called. That can't work with a constructor, because clone doesn't know which one to call. If a class is final, it can't have any subclasses, so there's no danger in calling its constructor when cloning.

这篇关于Effective Java:分析clone()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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