Object对象具体解释(二)之clone
clone方法会返回该实例对象的一个副本,通常情况下x.clone() != x || x.clone().getClass() == x.getClass() || x.clone().equals(x)也为真。但不严格要求,我们能够通过重写该方法来覆盖。
protected native Object clone() throws CloneNotSupportedException;
能够看到。clone是一个本地方法,可能会抛出CloneNotSupportedException异常,什么情况下会抛出呢?
/**
* A class implements the <code>Cloneable</code> interface to
* indicate to the {@link java.lang.Object#clone()} method that it
* is legal for that method to make a
* field-for-field copy of instances of that class.
* <p>
* Invoking Object's clone method on an instance that does not implement the
* <code>Cloneable</code> interface results in the exception
* <code>CloneNotSupportedException</code> being thrown.
* <p>
* By convention, classes that implement this interface should override
* <tt>Object.clone</tt> (which is protected) with a public method.
* See {@link java.lang.Object#clone()} for details on overriding this
* method.
* <p>
* Note that this interface does <i>not</i> contain the <tt>clone</tt> method.
* Therefore, it is not possible to clone an object merely by virtue of the
* fact that it implements this interface. Even if the clone method is invoked
* reflectively, there is no guarantee that it will succeed.
*
* @author unascribed
* @see java.lang.CloneNotSupportedException
* @see java.lang.Object#clone()
* @since JDK1.0
*/
public interface Cloneable {
}
说明中写到。假设该对象未实现Cloneable 接口。那么当实例调用clone方法时。就会抛出该异常。
以下看Object中对于clone方法的描写叙述。
/**
* Creates and returns a copy of this object. The precise meaning
* of "copy" may depend on the class of the object. The general
* intent is that, for any object {@code x}, the expression:
* <blockquote>
* <pre>
* x.clone() != x</pre></blockquote>
* will be true, and that the expression:
* <blockquote>
* <pre>
* x.clone().getClass() == x.getClass()</pre></blockquote>
* will be {@code true}, but these are not absolute requirements.
* While it is typically the case that:
* <blockquote>
* <pre>
* x.clone().equals(x)</pre></blockquote>
* will be {@code true}, this is not an absolute requirement.
* <p>
* By convention, the returned object should be obtained by calling
* {@code super.clone}. If a class and all of its superclasses (except
* {@code Object}) obey this convention, it will be the case that
* {@code x.clone().getClass() == x.getClass()}.
* <p>
* By convention, the object returned by this method should be independent
* of this object (which is being cloned). To achieve this independence,
* it may be necessary to modify one or more fields of the object returned
* by {@code super.clone} before returning it. Typically, this means
* copying any mutable objects that comprise the internal "deep structure"
* of the object being cloned and replacing the references to these
* objects with references to the copies. If a class contains only
* primitive fields or references to immutable objects, then it is usually
* the case that no fields in the object returned by {@code super.clone}
* need to be modified.
* <p>
* The method {@code clone} for class {@code Object} performs a
* specific cloning operation. First, if the class of this object does
* not implement the interface {@code Cloneable}, then a
* {@code CloneNotSupportedException} is thrown. Note that all arrays
* are considered to implement the interface {@code Cloneable} and that
* the return type of the {@code clone} method of an array type {@code T[]}
* is {@code T[]} where T is any reference or primitive type.
* Otherwise, this method creates a new instance of the class of this
* object and initializes all its fields with exactly the contents of
* the corresponding fields of this object, as if by assignment; the
* contents of the fields are not themselves cloned. Thus, this method
* performs a "shallow copy" of this object, not a "deep copy" operation.
* <p>
* The class {@code Object} does not itself implement the interface
* {@code Cloneable}, so calling the {@code clone} method on an object
* whose class is {@code Object} will result in throwing an
* exception at run time.
*
* @return a clone of this instance.
* @exception CloneNotSupportedException if the object's class does not
* support the {@code Cloneable} interface. Subclasses
* that override the {@code clone} method can also
* throw this exception to indicate that an instance cannot
* be cloned.
* @see java.lang.Cloneable
*/
protected native Object clone() throws CloneNotSupportedException;
当中提到的重写clone方法的几个注意点
1. 数组视为自己主动实现了Cloneable接口;
2. 非数组类型,使用clone方法,须要实现Cloneable接口。否则会抛出异常;
3. 非数组类型,克隆时,会新创建一个该类型的实例,并将被克隆对象实例的状态复制给新创建对象。而且这是一个浅克隆-(影子克隆——shallow copy),而不是deep copy;
4. 重写clone方法时。首先首先首先须要调用父类的clone方法。
那么问题来了。什么是shallow copy?而deep copy又是什么?
上样例:
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
People people = new People("zjh", '男', 21, new Cloth(COLOR.WHITE , "XXL"));
People clone = (People) people.clone();
System.out.println("people == clone : " + (people == clone));
System.out.println("people.getCloth() == clone.getCloth() : "+ (people.getCloth() == clone.getCloth()));
System.out.println("people.getAge() == clone.getAge() : "+(people.getAge() == clone.getAge()));
System.out.println("people.getName() == clone.getName() : "+(people.getName() == clone.getName()));
}
}
class People implements Cloneable{
private String name;
private char sex;
private int age;
private Cloth cloth;
/**
* {@inheritDoc}.
*/
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
...若干getter/setter方法
}
class Cloth{
private COLOR color;
private String size;
/**
* 构造函数.
*
* @param color
* @param size
*/
public Cloth(COLOR color, String size) {
super();
this.color = color;
this.size = size;
}
enum COLOR {
RED,WHITE,BLACK,GREEN,BLUE
}
}
执行结果:
people == clone : false
people.getCloth() == clone.getCloth() : true
people.getSex() == clone.getSex() : true
people.getName() == clone.getName() : true
age,sex。name比較为真还能理解,为什么people.getCloth() == clone.getCloth() 也是true呢?又做了以下的測试。
people.getCloth().setColor(COLOR.BLACK);
System.out.println(clone.getCloth().getColor());
执行结果:
BLACK
如今已经能确定,people和它的克隆对象clone中的cloth引用指向了同一个Cloth实例。这就是“shallow copy”。那么想要“deep copy”。那么就须要在重写方法的时候,同一时候调用对象属性的克隆方法(要求该属性对象也须要实现Cloneable)。
clone方法改动例如以下:
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
People clone = (People) super.clone();
clone.setCloth((Cloth)cloth.clone());
return clone;
}
再执行上面的測试程序:
people == clone : false
people.getCloth() == clone.getCloth() : false
people.getAge() == clone.getAge() : true
people.getSex() == clone.getSex() : true
people.getName() == clone.getName() : true
Object对象具体解释(二)之clone的更多相关文章
- Object对象具体解释(一)之toString
Object作为Java中超然的存在.当中定义了一切对象都共同拥有的方法. 特点: 1. java.lang包在使用的时候无需显示导入.编译时由编译器自己主动导入. 2. Object类是类层次结构的 ...
- Android 消息传递之Bundle的使用——实现object对象传输(二)
上面学习了线程通过Massage发送字符串消息,Handler接收字符串消息,这样的形式来更新ui,接下来,一起分享怎么把一个对象利用消息机制发送出去,让主线程接收来更新ui. 下面就利用一个服务Se ...
- java Object对象的clone方法
参考copy链接:http://blog.csdn.net/bigconvience/article/details/25025561 在看原型模式,发现要用到clone这个方法,以前和朋友聊过,没怎 ...
- Scala学习教程笔记二之函数式编程、Object对象、伴生对象、继承、Trait、
1:Scala之函数式编程学习笔记: :Scala函数式编程学习: 1.1:Scala定义一个简单的类,包含field以及方法,创建类的对象,并且调用其方法: class User { private ...
- js object对象赋值bug和对象复制clone方法
最近在写程序的时候发现,如果新建一个object对象objb,初始化值为obja,如果改变了objb对象的字段值,那么obja也会随之改变,看来对象赋值传递的是一个引用. 代码重现: <scri ...
- Object对象你真理解了吗?
前言 五一回家又断更了一个放假时间了~~~ 只有光头才能变强 回顾前面: ThreadLocal就是这么简单 多线程三分钟就可以入个门了! 多线程基础必要知识点!看了学习多线程事半功倍 Java锁机制 ...
- Java:Object对象小记
Java:Object对象小记 对 Java 中的 Object 对象,做一个微不足道的小小小小记 Object 的常用方法有哪些 clone() 方法:用于创建并返回当前对象的一份拷贝: 在Java ...
- Intent.putExtra()传递Object对象或者ArrayList<Object> (转)
Intent传递基本类型相信大家都十分熟悉,如何传递Object对象或者ArrayList<Object>对象呢? 可以通过: (1)public Intent putExtra (Str ...
- javascript ES5 Object对象
原文:http://javascript.ruanyifeng.com/stdlib/object.html 目录 概述 Object对象的方法 Object() Object.keys(),Obje ...
随机推荐
- .NET Core Run On Docker By Kubernetes 系列文章汇总
前言介绍 .NET Core是微软新一代主力编程平台,开源.免费.跨平台.轻量级.高性能,支持Linux.Docker.k8s等环境,适合开发微服务.云原生.大型互联网应用.全开源解决方案. Dock ...
- C语言和C++的应用领域都在哪些?学C语言好,还是学习C++好?
从事嵌入式开发十几年,基本上围绕着这两种编程语言展开,都可以直接操作底层的编程语言,用的越熟练越是感觉工具属性越强.虽然两种编程语言分属于不同的编程思想,用的时间长了觉得差异也不是很大,现在就个人的从 ...
- spark作业运行过程之--DAGScheduler
DAGScheduler--stage划分和创建以及stage的提交 本篇,我会从一次spark作业的运行为切入点,将spark运行过程中涉及到的各个步骤,包括DAG图的划分,任务集的创建,资源分配, ...
- 树莓派-基于raspivid实现拍视频
经过上一篇<<树莓派-安装摄像头模块>>之后 想要用摄像头模块拍一段视频的话,可以从命令行运行 raspivid 工具.下面这句命令会按照默认配置(长度5秒,分辨率1920x1 ...
- DeltaFish 校园物资共享平台 第二次小组会议
软工第二周小组会议 会议地点:三教讨论区 会议时间:9:00 ~ 10:00 与会人员:软工小组成员 请假人员:刘鼎乾 整理人:艾寅中 会议记录 一.小组分工 在经过一周的调研后,组长根据调研结果和对 ...
- ★Java面向对象(一)——————————基本概念
package boll; /* 用Java语言对现实生活中的事物进行描述. 通过类的形式来体现, 怎么描述呢? 对于事物的描述通常只有两个方面,一个是属性,一个是行为. 只要明确该事物的行为和属性并 ...
- We wanted {"required":["value"]} and you sent ["text","value","id","sessionId"]
重装python pycharm后再次执行以前执行没有问题的Appium脚本报错 We wanted {"required":["value"]} and yo ...
- drf05 路由Routers
对于视图集ViewSet,我们除了可以自己手动指明请求方式与动作action之间的对应关系外,还可以使用Routers来帮助我们快速实现路由信息. REST framework提供了两个router ...
- OAuth网络协议
一.应用场景 为了理解OAuth的适用场合,让我举一个假设的例子. 有一个"云冲印"的网站,可以将用户储存在Google的照片,冲印出来.用户为了使用该服务,必须让"云冲 ...
- NFS网络文件系统方案
1,关闭防火墙和selinuxiptables -Fsystemctl stop firewalldsystemctl disable firewalldsetenforce 0 服务器系统 名 ...