clone()
方法中的三个要求:x.clone() != x 为 true(这一条是必须的)
x.clone().getClass() == x.getClass() 为true
x.clone().equals(x) 为true(一般情况下为true,但这并不是必须要满足的要求)
由上图可以知道,如果Students对象中还有引用类型的数据,则还可以继续套娃克隆。
首先,clone()
是Object类下的一个方法:
protected native Object clone() throws CloneNotSupportedException;
该方法的修饰词为protected
和native
,所以如果要用这个方法,必须继承Object类。前文已经说到,浅克隆只通过clone()
即可,所以如果要进行深度克隆那么就需要对clone()
方法进行重写。此外,Java中Object类本身不实现Cloneable接口,所以类为Object的对象调用clone()
时需要抛出异常CloneNotSupportedException
。
clone()
方法两个步骤:
下面看一个对Animals
类重写的例子
class Animal implements Cloneable {
int age;
int weight;
SleepTime sleepTime;
public Animal(int age, int weight, SleepTime sleepTime) {
this.age = age;
this.weight = weight;
this.sleepTime = sleepTime;
}
//重写Animal的clone()
@Override
protected Animal clone() throws CloneNotSupportedException {
Animal animal = (Animal) super.clone();//先克隆Animal的基础数据类型属性
animal.sleepTime = this.sleepTime.clone();//再单独克隆Animal的引用数据类型
return (Animal) super.clone();
}
}
class SleepTime implements Cloneable {
int time;
public SleepTime(int time) {
this.time = time;
}
//重写SleepTime的clone()
@Override
protected SleepTime clone() throws CloneNotSupportedException {
return (SleepTime) super.clone();
}
}
super.clone()
相关在JavaDoc中关于clone
有这么一段
* 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.
上面这段话说人话就是:Object.clone()
有特殊的含义,即对当前对象进行浅克隆
综上对深度克隆中的super.clone()
就不难理解了
原文:https://www.cnblogs.com/youngsh4ker/p/14696825.html