javacloneable

How clone() method of object class works?


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?

Solution

  • 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.