<!-- @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:
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:
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:
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 }
发表评论
-
JAVA Developer Sites
2009-09-24 22:10 618<!--blog template--> ... -
About serialVersionUID
2009-10-07 10:13 600The serializat ... -
Java HOTSPOT VM参数大全
2009-10-08 11:22 629SUN的JDK版本从1.3.1开始使用HotSpot虚拟机技术 ... -
JVM的垃圾回收机制详解和调优
2009-10-09 22:52 591原文地址: http:// ... -
eclipse中jboss启动时提示50 seconds 超时之真正原因
2009-11-02 23:20 715eclipse中jboss启 ... -
Linux下JDK路径的配置
2009-11-15 10:18 6981:安装linux下的jdk ... -
在 Java 应用程序中定时执行任务
2009-12-15 12:14 629Java 中Timer 类的简洁用 ... -
Eclipse中JBOSS5.1无法启动的问题解决办法
2010-03-19 14:15 746今天在Eclipse中启动JBoss 5.1时 ... -
linux下java GUI中文字体显示问题
2010-07-10 09:35 901很早以前就发现Java GU ... -
OpenJDK的完美中文显示
2010-07-11 23:51 680在 <meta http-equiv="CON ... -
Log4j的PatternLayout
2010-07-28 18:50 712The PatternLayout is by far the ... -
Ant 基础
2010-10-05 21:11 542Ant 生成文件剖析 Ant 没有定义它自己的自定义语法;相 ... -
Ant文件操作
2010-10-06 09:08 5008创建和删除目录 最 ... -
Java is Pass-by-Value!
2010-10-17 15:02 788<!--blog template--> ... -
Java的继承
2010-10-24 16:53 692<!--blog template--> ...
相关推荐
How To Run Rapid Clone (adcfgclone.pl) Non-Interactively (Doc ID 375650.1)
See how a scripted installation method can be a fast and efficient way to provision ESX hosts. . Master ESX Native Tools Use tools like Esxtop to diagnose performance issues and vmkfstools to import ...
发表在NDSS‘16上的论How to Make ASLR Win the Clone Wars: Runtime Re-Randomization。这篇文章提出了一个RuntimeASLR的机制,让fork()出来的子进程内存空间地址重新随机化。 Background 在Apache,Nignx和OpenSSH...
Caffe2 Windows third_party(git clone失败或速度慢时可用)
Jlink-clone解决办法,替换文件
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...
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 ...
本人用的JLINK仿真器.在使用新版KEIL时,提示要升级固件,升级后就出现JLINK is Clone的提示。在网上找了许多关于修复的资料,都觉得不是很好。经过本人反复试验,总算找到比较好的解决方案,操作步骤如下
系统环境: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
how-to-write-a-node-cli-tools-with-commander 什么是cli tools? CLI(command-line interface,命令行界面)是指可在用户提示符下键入可执行指令的界面。 早启的unix/linux和DOS都是没有可视化界面的,那内存靠...
git clone 最新版 不多说上资源 好用测试ok git clong git clone 最新版 不多说上资源 好用测试ok git clong
Clone 属性的相关内容 Clone 属性的相关内容
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...
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...
Plus lots more mini-examples that show you how to write Components, how to use Forms, and how to use APIs The code examples currently have over 5,500+ lines of runnable code (TypeScript, non-comment ...
Clone10-EX-LV2
解决git clone时报错问题:sign_and_send_pubkey: signing failed: agent refused operation
jquery.clone
java中clone的详细用法,分浅拷贝和深拷贝,并分别有详细的实例介绍。从原理分析。
Minesweeper CLone 0.97 Saolei.net扫雷网,小门汉化 Men Shiyun Mine.exe 请自行下载MinesweeperClone_0.97.exe安装后使用