开发者

How does Object class implement clone() method

开发者 https://www.devze.com 2023-02-17 21:46 出处:网络
In a book on Core Java, I found this excerpt : Think about the way in which the Object class can implement clone. It

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?


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


Read this from the Javadoc:

protected Object clone() -

Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression:

x.clone() != x

will be true, and that the expression:

x.clone().getClass() == x.getClass()

will be true, but these are not absolute requirements. While it is typically the case that: x.clone().equals(x) will be true, this is not an absolute requirement. By convention, the returned object should be obtained by calling super.clone. If a class and all of its superclasses (except Object) obey this convention, it will be the case that

x.clone().getClass() == x.getClass().

By convention, the object returned by this method should be independent of this object (which is being cloned).

To achieve this independence, it may be necessary to modify one or more fields of the object returned by super.clone before returning it. Typically, this means copying any mutable objects that comprise the internal "deep structure" of the object being cloned and replacing the references to these objects with references to the copies. If a class contains only primitive fields or references to immutable objects, then it is usually the case that no fields in the object returned by super.clone need to be modified.

Means when you have a subobject in your object you shouldnt just clone/copy its reference but the internal structure of this object (in order to create a new instance of it), if each object has its clean clone() methode you will be able to clone it like the parent object otherwise you will have to create a new instance of it and copy its internal premitive fields one by one.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号