Create objects using Clone ()

Source: Internet
Author: User

All classes in the Java language inherit from the Java.lang.Object class by default, and in the Java.lang.Object class there is a clone () method, and the description of the JDK API explains that this method returns a copy of the object. We need to explain two points: first, the Copy object returns a new object, not the reference address of an object, and the difference between a copy object and a new object returned with the keyword operator is that the copy already contains information about the original object, not the object's initial information. That is, each copy action is not created for a new object.

When we use the New keyword to create an instance of a class, all constructors in the constructor are automatically called. But if an object implements the Cloneable interface, then we can call its clone () method, noting that the Clone () method does not call any constructors.

Code 3-1 shows a typical implementation of the factory pattern, where the factory pattern is a pattern that replaces the new operation with a factory method, so the factory pattern acts as the new operator that creates the instance object.

Code Listing 3-1 Creating a new object

public static Creditgetnewcredit ()

{

return new credit ();//Create a new credit object

}

If we use the Clone () method to create the object, the original information can be preserved, so the creation speed will be accelerated. As shown in Listing 3-2, the improved code uses the Clone () method.

Code Listing 3-2 uses the Clone () method

private static Creditbasecredit = new Credit ();

public static credit Getnewcredit ()

{

return (Credit) Basecredit.clone ();

}



Please pay attention to Uncle Mike every 10 o'clock in the evening said, let us communicate and study together.

Related Article

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.