Cloneable interface analysis

xiaoxiao2021-03-06  60

The Cloneable interface is a tag interface, that is, there is no content, defined as follows: package java.lang; Pubilc Interface Cloneable {} This interface is analyzed JAVA CLONE's meaning (or target) hypothesized X is a non-empty Objects should be: x.clone ()! = X is true, that is, they are not the same object .x.clone (). GetClass () == x.getClass () is True, they are the same type Class. x.Equals (x.clone ()) is TRUE, logically should be quite.

The Clone method is defined in Object, and it is protected by protected, only this interface is implemented.

The Clone method can be called on the instance of such a class, otherwise it will throw the default implementation in the clonenotsupportextectection.Object is a shallow copy, that is, the surface copy, if you need to achieve deep copy

If you have a new instance of the variable domain in the class. Pubilc class unsupported {public object clone () {Object Obj; try {obj = super.clone ();} catch (bronenotsupportedException ex) {EX.PrintStackTrace () // Exception Was thrown} return obj; // Returning null}} Plus IMPLEments Cloneable can be added. Can not be implemented, but override the clone method .pubilc class unnormal {public object clone () {Return New Unnormal ()}} This is certainly no problem, but it has not been related to the Clone mechanism in Java. Let's take an example for illustrative copy and 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 = (Deepco PY) super.clone ();} catch (clonenotsupportedException ex) {ex.printstacktrace ();} obj.setbegin ((Date) this.getbegin (). clone ()); return obj;}}

转载请注明原文地址:https://www.9cbs.com/read-119531.html

New Post(0)