Search code examples
javaclassobjectclone

How does Object class implement clone() method


In a book on Core Java, I found this excerpt :

Think about the way in which the Object class can implement clone. It knows nothing about the object at all, so it can make only a field-by-field copy. If all data fields in the object are numbers or other basic types, copying the fields is just fine. But if the object contains references to subobjects, then copying the field gives you another reference to the subobject, so the original and the cloned objects still share some information.

After reading this I was wondering, that How is the clone method originally implemented in Object Class?

What bothers me is that: how can a method in Object class make a field by field clone of a sub-class object, when it knows nothing about that class?


Solution

  • Actually, clone() is implemented in native code, so I assume it just does a memory copy (copy all the bytes) without knowing the contents.

    Besides that, there is the Reflection API to gain knowlegde about a class (which would be slower, however).