`
topzhujia
  • 浏览: 56011 次
  • 性别: Icon_minigender_1
  • 来自: 重庆
社区版块
存档分类
最新评论

How to write clone method

    博客分类:
  • JAVA
阅读更多

<!-- @page { margin: 2cm } P { margin-bottom: 0.21cm } --> By convention, the approach of writing clone method is:

1. Implements Cloneable interface

This approach ensures your clone method can directly or indirectly call Object.clone(). Otherwise, calling Object.clone() will throws CloneNotSupportedException. Why we need to call Object.clone() in our clone method? Please see approach 2.2.

2. Override the clone method

2.1 Make the clone method to public method

Please be noted that the clone method type of Object class is: protected Object clone() throws CloneNotSupportedException In order to support other class can use our clone method, we should define it as public method.

2.2 Call super.clone() to produce the new object

By convention, the object returned by clone method should be obtained by calling super.clone (this means it’s better to produce the new object by super.clone() than directly use “new” operator). If a class and all of its superclasses (except Object) obey this convention, it will be the case that x.clone().getClass() == x.getClass().

Key point: why we should use super.clone() to produce the new object instead of directly use “new” operator?

First of all, if all classes obey this convention, our clone method will directly or indirectly call Object.clone method. This method is a native method, it will be more efficient than directly “new” an object.

Secondly, Object.clone method can recognize the class type which called the clone method using RTTI mechanism. And it will return the new object which has the correct class type.

For example:

<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> 1 class A implements Cloneable
 2 class B extends A implements Cloneable {
 3 
 4     public Object clone() throws CloneNotSupportedException {
 5         B b = null;
 6 
 7         b = (B) super.clone(); // It seems that super.clone() is
 8                                            // A.clone(), so it will return an
 9                                            // object of Class A. This is incorrect.
10                                           // If the clone method of class A calls
11                                           // super.clone method too, it will
12                                           // return a new object belongs to
13                                           // class B. Thus, we can cast it to
14                                           // class B. This is the benefit of
15                                           // Object.clone().
16         return b;
17     }
18 }

Now, let’s consider another case, if we write clone method of class A like this:

<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->1 class A {
2     public Object clone() {
3         A a = null;
4         a = new A();
5         // Then do some copy data operation.
6         return a;
7    }
8 }

When B.clone() calls super.clone(),unfortunately we can only get the object whose class is A. And we can’t cast the new object to class B since B is a subclass of A.

That’s why it’s strongly recommended that clone method of all classes obey the convention that obtained the new object by calling super.clone().

2.3 Clone members

There are two cases: If the member supports clone, it’s better to call the clone method of the member to return a copy object of this member. If the member doesn’t support clone, you should create a new object which is the copy of the member. After this approach, it will be ensured that x.clone.equals(x) and x.clone() is independent with x.

Examples:

<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->  1 /**
  2  * class B support clone
  3  * 
  4  */
  5 class B implements Cloneable {
  6     private int intMember;
  7 
  8     public B(int i) {
  9         intMember = i;
 10     }
 11 
 12     public void setIntMember(int i) {
 13         intMember = i;
 14     }
 15 
 16     public Object clone() throws CloneNotSupportedException {
 17         B clonedObject = null;
 18 
 19         // Firstly, call super.clone to return new object
 20         clonedObject = (B) super.clone();
 21 
 22         // Secondly, clone member here
 23         clonedObject.setIntMember(intMember);
 24 
 25         // The end, return new object
 26         return clonedObject;
 27     }
 28 }
 29 
 30 /**
 31  * class C doesn't support clone
 32  * 
 33  */
 34 class C {
 35     private int intMember;
 36 
 37     public C(int i) {
 38         intMember = i;
 39     }
 40 
 41     public void setIntMember(int i) {
 42         intMember = i;
 43     }
 44 
 45     public int getIntMember() {
 46         return intMember;
 47     }
 48 }
 49 
 50 class A implements Cloneable {
 51     private int intMember = 0;
 52     private String stringMember = "";
 53     private B supportCloneMember = null;
 54     private C notSupportCloneMember = null;
 55 
 56     public void setIntMember(int i) {
 57         intMember = i;
 58     }
 59 
 60     public void setStringMember(String s) {
 61         stringMember = s;
 62     }
 63 
 64     public void setB(B b) {
 65         supportCloneMember = b;
 66     }
 67 
 68     public void setC(C c) {
 69         notSupportCloneMember = c;
 70     }
 71 
 72     public Object clone() throws CloneNotSupportedException {
 73         A clonedObject = null;
 74 
 75         // Firstly, call super.clone to return new object
 76         clonedObject = (A) super.clone();
 77 
 78         // Secondly, clone members here
 79 
 80         // For basic type member, directly set it to clonedObject
 81         // Because basic type parameter passes value. Modify
 82         // clonedObject.intMember can not effect the intMember
 83         // of itself.
 84         clonedObject.setIntMember(intMember);
 85         // For immutable member, directly set it to clonedObject.
 86         // Becasue we can not change the value of immutable
 87         // variable once it was setted.
 88         clonedObject.setStringMember(stringMember);
 89         // For member which support clone, we just clone it and
 90         // set the return object to the member of new object.
 91         B clonedB = (B) supportCloneMember.clone();
 92         clonedObject.setB(clonedB);
 93         // For member which do not support clone, we need to create
 94         // new object.
 95         C clonedC = new C(notSupportCloneMember.getIntMember());
 96         clonedObject.setC(clonedC);
 97 
 98         // The end, return new object
 99         return clonedObject;
100     }
101 }


分享到:
评论

相关推荐

    How To Run Rapid Clone (adcfgclone.pl) Non-Interactively (Doc ID

    How To Run Rapid Clone (adcfgclone.pl) Non-Interactively (Doc ID 375650.1)

    how-to-write-makefile:跟我一起写Makefile重制版

    跟我一起写Makefile &#40;PDF重制版&#41; 简介 《跟我一起写Makefile》是 发表在其CSDN博客上的系列文章。...$ git clone https://github.com/seisman/how-to-write-makefile.git 安装依赖: $ pip install -r

    How_to_Make_ASLR_Win_the_Clone_Wars__Runtime_Re-Randomization.pdf

    发表在NDSS‘16上的论How to Make ASLR Win the Clone Wars: Runtime Re-Randomization。这篇文章提出了一个RuntimeASLR的机制,让fork()出来的子进程内存空间地址重新随机化。 Background 在Apache,Nignx和OpenSSH...

    Jlink-clone解决办法,替换文件.rar

    当遇到"Jlink-clone"问题时,这通常指的是遇到了非原厂生产的、可能功能受限或者不稳定版本的J-Link设备。这类克隆设备可能会有兼容性问题、性能下降或不支持某些高级功能。本文将深入探讨如何解决Jlink-clone带来的...

    Jlink V8固件升级提示Clone的解决方法!

    在使用高版本版KEIL时,提示要升级固件,升级后就出现JLINK is Clone的提示!“the emulator is JLink-Clone, the segger software only support orginal segger device” 然后闪退,IDE崩溃关闭! 解决方案: 1....

    Getting Started with OpenCart Module Development

    Getting Started with OpenCart Module Development gives you step-by-step explanations and illustrations on how to clone, customize, and develop modules and pages with OpenCart. This book shows you how...

    java Clone

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

    解决 github项目clone报错 Failed connect to github.com:443; 解决

    系统环境:CentOS Linux release 7.6.1810 (Core) 起因:npm构建时报错 ... fatal: unable to access 'https://github.com/nhn/raphael.git/': Failed connect to github.com:443; Connection timed out npm

    java_clone用法

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

    Android代码-simplenote-android

    How to Configure Clone repo git clone https://github.com/Automattic/simplenote-android.git cd simplenote-android Import into Android Studio using the "Gradle" build option. You may need to create ...

    java clone的小例子

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

    clone()示例源码

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

    JLINK固件丢失或升级固件后提示Clone的解决办法

    本人用的JLINK仿真器.在使用新版KEIL时,提示要升级固件,升级后就出现JLINK is Clone的提示。在网上找了许多关于修复的资料,都觉得不是很好。经过本人反复试验,总算找到比较好的解决方案,操作步骤如下

    how-to-write-a-node-cli-tools-with-commander:How-to-write-a-node-cli-tools-with-commander

    how-to-write-a-node-cli-tools-with-commander 什么是cli tools? CLI(command-line interface,命令行界面)是指可在用户提示符下键入可执行指令的界面。 早启的unix/linux和DOS都是没有可视化界面的,那内存靠...

    java clone

    在Java编程语言中,`clone`是一个非常重要的概念,它涉及到对象复制和对象克隆。本文将深入探讨Java中的`clone`方法,包括其工作原理、使用场景、注意事项以及一些个人实践心得。 首先,让我们理解什么是`clone`。...

    git clone 最新版

    "git clone"是Git中的一个核心命令,用于复制远程仓库到本地。在本文中,我们将深入探讨`git clone`命令以及如何获取其最新版本。 首先,让我们了解`git clone`的基本用法。当你运行`git clone &lt;repository&gt;`时,它...

    jlink v9 warning clone解决

    `jlink v9 warning clone`问题通常涉及到JLink版本9在与MDK配合使用时遇到的警告,提示可能与克隆设备或非法设备相关。 标题中的"jlink v9 warning clone解决"意味着开发者正在尝试解决关于JLink v9版本出现的克隆...

    CLONE 10-ex

    标题“CLONE 10-ex”以及描述“Clone10-EX-LV2”暗示了我们正在处理一个可能与克隆或复制技术相关的项目,可能是软件、系统镜像或者某种形式的数据备份工具。"Clone"通常指的是在计算机科学中创建一个与原始对象完全...

    《5 Practical React Projects》2017 英文原版 Kindle - mobi格式

    How to Create a Reddit Clone Using React and Firebase by Nirmalya Ghosh Build a CRUD App Using React, Redux and FeathersJS by Michael Wanyoike How to Build a Todo App Using React, Redux, and Immutable...

    Object-C-MixinObject-C-MixinObject-C-Mixin

    It's a good start to understand how to write mixin in Object-C. ### Import ObjCMixin ```objc #import ``` ### Define and implement a module Declare a module. ```objc @module(MyModule) @property...

Global site tag (gtag.js) - Google Analytics