About Java's clone method and Cloneable interface

Effective Java Item 11: Override cloneCarefully. After careful reading, we can go further and conclude that other interfaces should not inherit ( extendsextend) the Cloneableinterface, and other classes should not implement ( implements) the interface. If you really need deep (memory) copies of objects, consider using serialization and deserialization instead.

For a clonemethod, it is a shallow copy. If the copied class holds other class variables, it must be implemented by the defining class of this class variable Copy Constructor.

Another good way to implement object copying is to provide a copy constructor ( copy constructor) or a copy factory ( copy factory). A copy constructor is just a constructor whose only parameter type is the class containing the constructor, for example:

public Yum(Yum yum)  

A copy factory is a static factory similar to a copy constructor:

public static Yum newInstance(Yum yum)  

The copy-constructor approach, and its variants of static factory methods, Cloneable/clonehave the advantage over methods that they do not depend on some risky, extra-language object creation mechanism; they do not require compliance that has not yet been established documentation; they do not conflict with the normal use of final fields; they do not throw unnecessary checked exceptions ( check exception); they do not require type conversions.

While you can't put a copy constructor or static factory in an interface, it doesn't provide the features an interface should have because it Cloneablelacks a public method. cloneTherefore, using a copy constructor or a copy factory instead of a clonemethod does not give up the functional properties of the interface.

Furthermore, a copy constructor or copy factory can take a parameter whose type is the interface implemented by the class. For example, by convention, all generic collections provide a copy constructor whose argument is of type Collectionor Map.

Interface-based copy constructors and copy factories (more precisely called 'conversion constructors conversion constructor') and conversion factories ( conversion factory)) allow the client to choose the implementation type of the copy, rather than forcing the user to accept the original implementation type. For example, let's say you have one HashSet, and want to copy it into one TreeSet, clonethe method doesn't provide such functionality, but it's easy to do with the conversion constructor: new TreeSet(s).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325768272&siteId=291194637