How clone() method of object class works?

95 Views Asked by At

Object class clone() method has native implementation which creates instance of child class and copies the state of source object to newly created instance.

Question:

  1. clone() method of object class doesn't invoke constructor of child class then how does it creates instance of the child class?
2

There are 2 best solutions below

0
On BEST ANSWER

Clone is implemented within the JVM in an implementation dependant way. In OpenJDK, clone is implemented as jvm_clone in jvm.cpp from line 627. This allocates the memory for the object and copies the data from the object it was called on.

Creating an instance and calling constructors are separate operations at the JVM level so native implementations don't need to call any constructor after creating an instance. By using the lower level JVM methods in C++ it doesn't need to call the constructor.

3
On

Your definition is false. The clone() method does not create an instance of the child class, instead, it creates an instance of the class where the clone() method was called. This instance containing all of its current values. For this reason, it does not call the child class constructor, however, it does call the constructor of its own class.