The clone
method on Object
, which creates an exact copy of an object, is declared as:
protected native Object clone() throws CloneNotSupportedException;
Why is it native
?
The clone
method on Object
, which creates an exact copy of an object, is declared as:
protected native Object clone() throws CloneNotSupportedException;
Why is it native
?
Basically, because the
clone()
method does something that you cannot do in the Java language: it clones the state the of the object, including its actual class designation.The cloning mechanism in Java is based on each class calling the superclass's
clone
method, all the way up toObject
. Object then uses this "magical" nativeclone
method to duplicate the original object, including its actual class.Think of this:
Now imagine that you have a
B
type object, and you callclone
on it. You expect to get aB
object, whose class is internally recognized asB
, not asObject
.B
doesn't know the implementation of everything inA
, and therefore it needs to callA
'sclone
method. But ifA
implementedclone
in the Java language rather than callingsuper.clone()
, then the object it would return would have to beA
. It cannot usenew B()
(assume B was not known when A was created).It could do something with reflection, but how would it know which constructor to call so that all the final fields would be properly filled up?
So the trick is that
A
doesn't do it itself, it callssuper.clone()
, and this goes all the way back toObject
, and it uses a native method that does a byte-by-byte copying of the original object, adjusting for the new heap location. Thus, the new object magically becomes aB
object and the type casting would not fail.Why not return an
Object
then? Because that would not be cloning. When you callclone
you expect to get an object of both the same state (fields), and the same class (overridden and added methods). If it returned an object whose internal class designation wasObject
, you'd only have access to things thatObject
offers, such astoString()
, and you would not be able to access its private fields from anotherB
object, or to assign it to aB
type variable.It is native, because some system classes'
Clone()
method are written in C++ to improve performance.Look at the clone documentation:
This operation can be done very efficiently with native code, as some memory has to be copied directly. It is similar in that regard to
System.arrayсopy
, which is also native. For details see this question: Is it possible to find the source for a Java native method?Note that usually you should avoid Object.clone(), and use for example a copy constructor instead, see How do I copy an object in Java?