`
leonzhx
  • 浏览: 791569 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Item 11: Override clone judiciously

阅读更多

1.  The Cloneable interface was intended as a mixin interface for objects to advertise that they permit cloning. However it lacks a clone method, and Object’s clone method is protected.

 

2.  If a class implements Cloneable, Object’s clone method returns a field-by-field copy of the object; otherwise it throws CloneNotSupportedException.

 

3.  Java specification requires that cloning an object will typically entail creating a new instance of its class, but it may require copying of internal data structures as well. No constructors are called.

 

4.  In practice, programmers assume that if they extend a class and invoke super.clone from the subclass, the returned object will be an instance of the subclass. If you override the clone method in a non-final class, you should return an object obtained by invoking super.clone. If all of a class’s superclasses obey this rule, then invoking super.clone will eventually invoke Object’s clone method, creating an instance of the right class.

 

5.  In practice, a class that implements Cloneable is expected to provide a properly functioning public clone method.

 

6.  The fields declared in your class (if any) will have values identical to those of the object being cloned by super.clone() if all the clone methods of super classes behave well. If every field contains a primitive value or a reference to an immutable object, the returned object may be exactly what you need.

 

7.  Because Object.clone returns Object, you must cast the result of super.clone() before returning it.

 

8.  In effect, the clone method functions as another constructor; you must ensure that it does no harm to the original object and that it properly establishes invariants on the clone.

 

9.  Calling clone on an array returns an array whose compile-time type is the same as that of the array being cloned. (instead of Object)

 

10.  The clone architecture is incompatible with normal use of final fields referring to mutable objects.

 

11.  Like a constructor, a clone method should not invoke any non-final methods on the clone under construction. If clone invokes an overridden method, this method will execute before the subclass in which it is defined has had a chance to fix its state in the clone, quite possibly leading to corruption in the clone and the original.


12.  Public clone methods should omit the CloneNotSupportedException because methods that don’t throw checked exceptions are easier to use.

 

13.  If a class that is designed for inheritance, the overriding clone method should mimic the behavior of Object.clone: it should be declared protected, it should be declared to throw CloneNotSupportedException, and the class should not implement Cloneable. This gives subclasses the freedom to implement Cloneable or not, just as if they extended Object directly.

 

14.  To recap, all classes that implement Cloneable should override clone with a public method whose return type is the class itself. This method should first call super.clone and then fix any fields that need to be fixed. Typically, this means copying any mutable objects that comprise the internal “deep structure” of the object being cloned, and replacing the clone’s references to these objects with references to the copies. While these internal copies can generally be made by calling clone recursively, this is not always the best approach. If the class contains only primitive fields or references to immutable objects, then it is probably the case that no fields need to be fixed. There are exceptions to this rule. For example, a field representing a serial number or other unique ID or a field representing the object’s creation time will need to be fixed, even if it is primitive or immutable.

 

15.  A fine approach to object copying is to provide a copy constructor or copy factory. A copy constructor is simply a constructor that takes a single argument whose type is the class containing the constructor. A copy factory is the static factory analog of a copy constructor.

 

16.  The copy constructor approach and its static factory variant have many advantages over Cloneable/clone: they don’t rely on a risk-prone extralinguistic object creation mechanism; they don’t demand unenforceable adherence to thinly documented conventions; they don’t conflict with the proper use of final fields; they don’t throw unnecessary checked exceptions; and they don’t require casts.

 

17.  A copy constructor or factory can take an argument whose type is an interface implemented by the class. For example, by convention all general purpose collection implementations provide a constructor whose argument is of type Collection or Map. Interface-based copy constructors and factories, more properly known as conversion constructors and conversion factories, allow the client to choose the implementation type of the copy rather than forcing the client to accept the implementation type of the original.

分享到:
评论

相关推荐

    Effective Java 3rd edition(Effective Java第三版英文原版)附第二版

    Item 11: Always override hashCode when you override equals Item 12: Always override toString Item 13: Override clone judiciously Item 14: Consider implementing Comparable 4 Classes and Interfaces Item...

    对话框VC源代码:override_fontdlg

    在VC++编程环境中,"override_fontdlg"是一个特定的对话框功能实现,它涉及到了对话框的自定义和字体选择的交互。对话框是Windows应用程序中常见的一种用户界面元素,通常用于收集用户输入或者显示一些信息。在这个...

    Delphi面向对象:overload与override[文].pdf

    Delphi面向对象编程之overload与override Delphi面向对象编程中,overload和override是两个非常重要的概念,它们都是面向对象编程的基础概念。本文将详细介绍overload和override的概念、应用场景及实现方法。 一、...

    TOMO-CAT#CppNote#override和final1

    C++11关键字:override和final场景在传统C++中,经常容易发现意外重载虚函数的事情:struct SubClass: Base {有下列三种非预

    java Clone

    Java中的`clone`方法是Java语言提供的一种复制对象的方式,它允许创建一个对象的副本,这个副本与原对象具有相同的属性值,但它们是两个独立的对象,修改副本不会影响原对象。`clone`方法存在于Java的`java.lang....

    java_clone用法

    ### Java中的`clone`方法详解:浅拷贝与深拷贝 #### 一、引言 在Java中,`clone`方法提供了一种快速复制对象的方式。它属于`Object`类的一部分,但需要显式地在子类中声明并实现`Cloneable`接口才能正常使用。本文...

    java clone的小例子

    在Java编程语言中,`clone()`方法是一个非常重要的概念,特别是在对象复制和克隆方面。这个小例子将帮助初学者理解如何在Java中使用`clone()`来创建对象的副本。让我们深入探讨`clone()`方法以及它在实际编程中的...

    android @override 报错解决方案

    现象: … java: 1801: method does not override a method from its superclass @Override… 原因: Eclipse is defaulting to Java 1.5 and you have classes implementing interface methods (which in Java 1.6 ...

    深入理解c++11pdf

    《深入理解C++11》是一本专注于C++11标准新特性的解析与应用的书籍,其中涉及了语言的诸多改进和优化。在第二章中,主要讨论了如何通过`final`和`override`关键字确保类的稳定性和兼容性。 在C++11之前,多态性依赖...

    Override错误已解决

    ### Override 错误详解与解决方案 #### 一、概述 在进行 Java 开发的过程中,特别是在使用 Eclipse 这样的集成开发环境(IDE)时,开发者可能会遇到一个常见的问题:`Override` 错误。这种错误通常发生在尝试覆盖...

    ListView选中item颜色改变

    考虑到Android系统的版本差异,对于API 11及以上版本,可以使用`setChoiceMode()`和`setItemChecked()`方法来实现更简洁的选中效果,如下: ```java listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); // ...

    clone()示例源码

    在Java编程语言中,`clone()`方法是一个非常重要的概念,特别是在处理对象复制和克隆时。这个方法源自`Object`类,是所有Java类的基类。`clone()`的使用通常涉及到深度复制和浅复制的概念,这两者在数据结构和内存...

    《 Menu详解(二):利用XML生成菜单和子菜单》源码

    每个菜单项通常用`<item>`标签表示,如下: ```xml <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/action_item1" android:icon="@drawable/ic_item1" android:...

    android 菜单演示

    子菜单的点击事件处理与普通菜单类似,但需要确保菜单项具有子菜单,并在`onOptionsItemSelected(MenuItem item)`中检查子菜单的存在。 通过以上的实践,你可以创建丰富的菜单结构,提升Android应用的用户体验。在...

    effectice_java第二版 英文

    9. **条目9:谨慎地覆盖clone(Override clone judiciously)** clone()方法可能存在复杂性和陷阱,除非有必要,否则应避免覆盖。 10. **条目10:优先考虑使用枚举而非int常量(Use Enums Instead of Int ...

    Java深浅clone

    在Java编程语言中,`Cloneable`接口和`clone()`方法是两个重要的概念,它们用于对象复制。在本文中,我们将深入探讨Java中的浅克隆(shallow clone)和深克隆(deep clone),并结合测试代码进行分析。 首先,让...

    Android实现二级菜单和标题栏菜单

    android:id="@+id/action_item1" android:title="一级菜单项1"/> <item android:id="@+id/action_item2" android:title="一级菜单项2"/> ``` 2. 在`Activity`中实现`onCreateOptionsMenu()`: ```java @...

    Listview点击item高亮显示,

    @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // 取消之前选中的项 if (lastSelectedPosition != -1) { parent.getChildAt(lastSelectedPosition)....

    android listview item背景色点击效果实例

    @Override public View getView(int position, View convertView, ViewGroup parent) { View itemView = convertView; if (itemView == null) { itemView = LayoutInflater.from(getContext()).inflate(R....

    new,override,virtual 示例

    在C#编程语言中,`new`、`override`和`virtual`是三个非常重要的关键字,它们用于控制类成员(主要是方法)的行为,涉及到多态性这一核心概念。接下来我们将详细探讨这三个关键字以及它们在实际编程中的应用。 1. `...

Global site tag (gtag.js) - Google Analytics