克隆时为什么不执行构造函数

Animal animal = new Animal(101); //Constructor is executed. Animal clone=(Animal)animal.clone() //Constructor is not executed. Why ? 

Object类中给出的clone()方法的默认实现不会调用任何类型的构造函数。

它是对象的“浅层副本”,因为它通过创建新实例然后通过赋值复制内容来创建Object的副本,这意味着如果您的类包含可变字段,则原始对象和克隆都将引用相同的内部对象

试着看看这个页面。

您的构造函数未调用,因为您正在调用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); } } 

现在,每次调用clone方法时,都会调用复制构造函数(带有A参数的复制构造函数)。

对我说