Object objects in detail (i) clone

Source: Internet
Author: User

The Clone method returns a copy of the instance object, typically X.clone ()! = X | | X.clone (). GetClass () = = X.getclass () | | X.clone (). Equals (x) is also true, but is not strictly required, and we can override this method by overriding it.

protectednativeclonethrows CloneNotSupportedException;

As you can see, clone is a local method that may throw a clonenotsupportedexception exception, and under what circumstances will it be thrown?

/** * AclassImplements the<code>Cloneable</code> interface to* Indicate to  the{@link Java.lang.Object#clone ()} method that it* isLegal for  thatMethod toMake A * field- for-fieldCopy  ofInstances of  that class. * <p> * Invoking Object ' s Clone method onAn instance that does  notImplement the* <code>Cloneable</code> Interface Resultsinch  theException * <code>CloneNotSupportedException</code> being thrown. * <p> * By convention, classes thatImplement this interface should override * <tt>Object.clone</tt> (which isProtected withA public method. * See {@link java.lang.Object#clone ()} for details on overriding this* method. * <p> * Note thatThis interfacedoes<i> not</i>contain  the<tt>clone</tt> method. * Therefore,it  is  notPossible toClone an object merely byVirtue of  the* Fact that itImplements this interface. Evenif  theClone method isInvoked * reflectively, there isNo guarantee that itwould succeed. * * @author unascribed * @see java.lang.CloneNotSupportedException * @see java.lang.Object#clone ()* @sinceJDK1. 0*/public interface Cloneable {}

The description writes that if the object does not implement the Cloneable interface, the exception is thrown when the instance calls the Clone method.
The following is a description of the Clone method in object.

/** * Creates andReturns aCopy  ofThis object. The precise meaning * of "Copy"May depend on  the class  of  theObject. The general * Intent is  that, forAny object {@code x}, theExpression: * <blockquote> * <pre> * x.clone ()! = x</pre></blockquote> * 'll betrue, and  that  theExpression: * <blockquote> * <pre> * X.clone (). GetClass () = = X.getclass () </pre></blockquo Te> * would be {@codetrue}, butThese is notAbsolute requirements. * Whileit  isTypically theCase that: * <blockquote> * <pre> * x.clone ().equals(x) </pre></blockquote> * 'll be {@codetrue}, this is  notAn absolute requirement. * <p> * By convention, theReturned object should be obtained byCalling * {@code super.clone}. If Aclass  andAll of  itsSuperclasses (except * {@code Object}) obey this convention,itwould be theCase that* {@code x.clone (). GetClass () = = X.getclass ()}. * <p> * By convention, theObject returned byThis method should is independent * ofThis object (which isBeing cloned). To achieve this independence, *itmay be necessary toModify OneorMore fields of  theObject returned * by{@code Super.clone}before returning it. Typically, this means * copying any mutable objects thatcomprise theInternal"Deep Structure"* of  theObject being cloned andReplacing theReferences toThese * objects withReferences to  theCopies. If Aclass contains* Primitive fieldsorReferences toImmutable objects, Then it  isusually * theCase thatNo fieldsinch  theObject returned by{@code Super.clone} * need toBe modified. * <p> * The method {@code clone} for class{@code Object} performs a * specific cloning operation. First,if  the class  ofThis objectdoes* notImplement theinterface {@code cloneable}, ThenA * {@code clonenotsupportedexception} isThrown. Note thatAll arrays * is considered toImplement theinterface {@code cloneable} and  that* the returnType of  the{@code Clone} method ofAn array type {@code t[]} * is{@code t[]}whereT isAnyReference orPrimitive type. * Otherwise, this method creates a new instance of  the class  ofThis * object andInitializes all itsFields withExactly the Contents  of* thecorresponding fields ofThis object, as if  byassignment; the*Contents  of  theFields is notthemselves cloned. Thus, this method * performs a"Shallow copy"  ofThis object, notA"Deep Copy"Operation. * <p> * Theclass{@code Object}does  notitself implement theInterface * {@code cloneable}, so calling the{@code Clone} method onAn object *whose class  is{@code Object} wouldresult inchThrowing an * exception at Run  Time. *     * @returnA clone ofThis instance. * @exception clonenotsupportedexceptionif  theObject ' sclass does  not* Support the{@code Cloneable} interface. Subclasses * thatOverride the{@code Clone} method can also * throw this exception toIndicate thatAn instance cannot * is cloned. * @see java.lang.Cloneable */protected native Object clone () throws Clonenotsupportedexception;

Several points of note that are mentioned in overriding the Clone method
1. The array is considered to automatically implement the Cloneable interface;
2. Non-array type, using the Clone method, you need to implement the Cloneable interface, otherwise it will throw an exception;
3. Non-array type, when cloning, a new instance of the type is created, and the state of the cloned object instance is copied to the newly created object, and this is a shallow clone-(shadow clone--shallow copy), not deep copy;
4. When overriding the Clone method, first you first need to call the parent class's Clone method.

So here's the question, what is shallow copy? And what is deep copy?

above example:

 Public  class Test {     Public Static void Main(string[] args)throwsclonenotsupportedexception {People people =NewPeople ("Zjh",' man ', +,NewCloth (COLOR. White,"XXL"));          People clone = (people) People.clone (); System.out.println ("People = = Clone:"+ (People = = clone)); System.out.println ("people.getcloth () = = Clone.getcloth ():"+ (People.getcloth () = = Clone.getcloth ())); System.out.println ("people.getage () = = Clone.getage ():"+ (people.getage () = = Clone.getage ())); System.out.println ("people.getname () = = Clone.getname ():"+ (people.getname () = = Clone.getname ())); }}class people implements cloneable{PrivateString name;Private CharSexPrivate intAgePrivateCloth cloth;/** * {@inheritDoc}. */    @Override    protectedObjectClone()throwsclonenotsupportedexception {//TODO auto-generated method stub        return Super. Clone (); }    ... Several getter/setter methods}class cloth{PrivateColor color;PrivateString size;/** * constructor function. * * @param color * @param size */     Public Cloth(color color, String size) {Super(); This. color = color; This. size = size; }enumCOLOR {Red,white,black,green,blue}}

Operation Result:

People = = Clone:false
People.getcloth () = = Clone.getcloth (): True
People.getsex () = = Clone.getsex (): True
People.getname () = = Clone.getname (): True

Age,sex,name comparison is true and can understand, why people.getcloth () = = Clone.getcloth () is also true? The following tests were done.

 people.getCloth().setColor(COLOR.BLACK);          System.out.println(clone.getCloth().getColor());

Operation Result:

BLACK

It is now possible to determine that the cloth reference in people and its clone object clone points to the same cloth instance. This is "shallow copy". If you want to "deep copy" then you need to invoke the Clone method of the object property at the same time when overriding the method (requires that the Property object also implements Cloneable).

The Clone method is modified as follows:

    protectedclone() throws CloneNotSupportedException {        // TODO Auto-generated method stub        clone =    (People) super.clone();        clone.setCloth((Cloth)cloth.clone());        returnclone;    }

Then run the above test program:

People = = Clone:false
People.getcloth () = = Clone.getcloth (): false
People.getage () = = Clone.getage (): True
People.getsex () = = Clone.getsex (): True
People.getname () = = Clone.getname (): True

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Object objects in detail (i) Clone

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.