The Cloneable interface is a markup interface that has no content, defined as follows:
Package Java.lang;
Pubilc Interface cloneable{
}
Here, analyze the usage of this interface
Meaning of Java clone (or target)
Suppose X is a Non-empty object and should have:
X.clone ()!=x is true, which means they are not the same object.
X.clone (). GetClass () ==x.getclass () is true, they are of the same type class.
X.equals (X.clone ()) is true and logically should be equivalent.
The Clone method is defined in the object type and is protected, and only the interface is implemented
You can invoke the Clone method on an instance of the class, or you will throw a clonenotsupportexception.
The default implementation in object is a shallow copy, which is a surface copy, if you need to implement a deep copy
, you must generate a new instance of the mutable domain in the class.
Pubilc class unsupported{
Public Object Clone () {
Object obj;
try {
Obj=super.clone ();
}
catch (Clonenotsupportedexception ex) {
Ex.printstacktrace (); Exception was thrown
}
return obj;//returns null
}
}
Plus implements cloneable is OK.
You can not implement this interface, but overwrite the Clone method.
Pubilc class unnormal{
Public Object Clone () {
return new Unnormal ();
}
}
This is definitely fine, but it has nothing to do with the clone mechanism in Java.
Here is an example of a shallow copy and a deep copy:
public class Shallowcopy implements cloneable{
Private Date begin;
Public Date Getbegin () {return this.begin;}
public void SetBegin (Date d) {This.begin=d}
Public Object Clone () {
Object Obj=null;
Try
{
Obj=super.clone ();
}
catch (Clonenotsupportedexception ex) {
Ex.printstacktrace ();
}
return obj;
}
}
public class Deepcopy implements cloneable{
Private Date begin;
Public Date Getbegin () {return this.begin;}
public void SetBegin (Date d) {This.begin=d}
Public Object Clone () {
Deepcopy Obj=null;
Try
{
obj= (deepcopy) Super.clone ();
}
catch (Clonenotsupportedexception ex) {
Ex.printstacktrace ();
}
Obj.setbegin ((Date) This.getbegin (). Clone ());
return obj;
}
}