为什么克隆时不执行构造函数
Why constructor is not executed while cloning
Animal animal = new Animal(101); //Constructor is executed.
Animal clone=(Animal)animal.clone() //Constructor is not executed. Why ?
Object
class 中给出的 clone()
方法的默认实现不调用任何类型的构造函数。
它创建一个 "shallow copy" 对象,因为它通过创建新实例然后通过赋值复制内容来创建对象的副本,这意味着 如果您的 Class 包含一个可变对象字段,则原始对象和克隆对象将引用相同的内部对象.
尝试查看 this 页面。
您的构造函数未被调用,因为您正在调用 clone() 方法。
根据clone方法的实现方式,不需要调用构造函数。
涉及构造函数的一种方法是使用复制构造函数实现克隆方法,如下所示:
public class A implements Cloneable{
private int example;
public A(){
//this is the default constructor, normally not visible and normally not needed,
//but needed in this case because you supply another constructor
}
public A(A other){
this.example = other.example;
}
//You may specify a stronger type as return type
public A clone(){
return new A(this);
}
}
现在,每次调用克隆方法时,都会调用复制构造函数(带有 A 参数的构造函数)。
问候
我
Animal animal = new Animal(101); //Constructor is executed.
Animal clone=(Animal)animal.clone() //Constructor is not executed. Why ?
Object
class 中给出的 clone()
方法的默认实现不调用任何类型的构造函数。
它创建一个 "shallow copy" 对象,因为它通过创建新实例然后通过赋值复制内容来创建对象的副本,这意味着 如果您的 Class 包含一个可变对象字段,则原始对象和克隆对象将引用相同的内部对象.
尝试查看 this 页面。
您的构造函数未被调用,因为您正在调用 clone() 方法。 根据clone方法的实现方式,不需要调用构造函数。
涉及构造函数的一种方法是使用复制构造函数实现克隆方法,如下所示:
public class A implements Cloneable{
private int example;
public A(){
//this is the default constructor, normally not visible and normally not needed,
//but needed in this case because you supply another constructor
}
public A(A other){
this.example = other.example;
}
//You may specify a stronger type as return type
public A clone(){
return new A(this);
}
}
现在,每次调用克隆方法时,都会调用复制构造函数(带有 A 参数的构造函数)。
问候 我