Clone of Java.lang.Object () use

Source: Internet
Author: User

All Java classes inherit the Java.lang.Object class by default, and there is a Method clone () in the Java.lang.Object class. The documentation for the JDK API explains that this method will return a copy of the object. There are two points to note: one is that the Copy object returns a new object, not a reference. Second, the difference between a copy object and a new object returned with the newly operator is that the copy already contains information about the original object, not the object's initial information.
There are a few things to note about using the Clone () method in Java

1: The Clone class must implement the Cloneable interface, the Cloneable interface is actually an identity interface, there is no interface method, if not implemented Cloneable interface will be reported java.lang.CloneNotSupportedException.

2: The class implementing the Cloneable interface should use a public method to rewrite Object.clone () (It is protected). It is not possible to clone an object that implements this interface. Even if the clone () method is a reflexive call, there is no guarantee that it will succeed.

3: When writing the Clone () method, there is usually a line of code super.clone (); Clone has a default behavior, Super.clone (); Because the first thing to do is to copy the members of the parent class into place, and then copy their own members.

 Public class Implements cloneable {    @Override    public  Clone Clone () {        try  {             Super . Clone ();             return clone;         Catch (clonenotsupportedexception e) {            thrownew  internalerror (e);}}    } 

Clone of Java.lang.Object () use

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.