简体   繁体   English

为什么在克隆 java 中的 object 时不调用构造函数

[英]Why the Constructor is not called while cloning the object in java

Why is the constructor is not called while cloning an object in java?为什么在 java 中克隆 object 时不调用构造函数?

Animal a = new Animal();
Animal b = (Animal)a.clone(); // This will not invoke Animal's constructor

If an object is created which is referenced by variable b then there would be some memory allocation and that should also involve calling the constructor, right?如果创建了一个由变量 b 引用的 object,那么将会有一些 memory 分配,这也应该涉及调用构造函数,对吧?

But the documentation says, cloning an object does not involve calling the constructor calling at all.但是文档说,克隆 object 根本不涉及调用构造函数。 Why?为什么?

Also I cannot descibe why it is like it is.我也无法描述为什么会这样。 It seems that Java is just using another functionality to clone and make a copy of an object in constrast to creating new objects via new keyword.似乎 Java 只是使用另一个功能来克隆和复制 object 以通过 new 关键字创建新对象。 Using clone() means that the clone is created and all values are copied and the references are also copied.使用 clone() 意味着创建了克隆,复制了所有值,也复制了引用。 So clone() does not produce new objects with new references of the referenced objects.因此 clone() 不会产生具有被引用对象的新引用的新对象。 Maybe clone() is a kind of constructor?也许 clone() 是一种构造函数?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM