About Cloneable interface

Understand and use interface Cloneable

The role of 1.Cloneable interface

First we look at the inside of the Object class clone method:
Object class clone method
First, we can see that the clone method is a method labeled native keyword, native is a modified method empty, but not the same as modified and abstract, abstract modification means that we need to specific implementation class implementation of this method, native method indicates that this method is not a Java implementation, but the language is implemented by a third party, they will be in the JVM by a specific implementation body.

Secondly, we look at the method throws an exception, CloneNotSupportedException, which translates to clone this method is not supported, so you can use the time may throw an exception.

This time we should know that you want to use this method must return to our theme Cloneable interface, Cloneable interface is actually a marker interface only implements this interface to override the clone method.

Effects achieved clone method is to copy the object. Are two copies of the object a potential copying a deep copy

Shallow copy:
the definition of a person class
person
in the definition of a Home class:
home category
Test class:
Test category
Output:
Export
This time, we found HashCode Home object is not the same, indicating that these are two different objects, but HashCode Person object is the same, that this is an object, because that is the Home class implements the Cloneable interface to override the clone method.
For example:
ClassName c = new new ClassName ();
ClassName c2 = c;
this way hashCode c and c2 are the same, he just copied handles, both handles operations is the same object. This realization has nothing to do with class Cloneable interface

But to achieve the Cloneable interface, using the clone method when memory space will be re-opened, the two HashCode is also not the same, indicating that these two are not the same object handles operations.

Released six original articles · won praise 0 · Views 106

Guess you like

Origin blog.csdn.net/Chenpeng02/article/details/95449089