Clone of objects in Java

Source: Internet
Author: User

Clone of objects in Java

1. Declare and implement the cloneable interface and rewrite the clone method. If this method is not overwritten, the clone method of the object cannot be called.
2. call the super. clone to get an object. If there is no problem with the clone Implementation of the parent class, all fields defined by the parent class have been cloned in the memory storage of the object, the value type fields and reference type fields in this class are also cloned, but the currently referenced type fields are all shortest copies.
3. Point the reference of the shortest copy to the new clone of the prototype object.

 

public class Person implements Cloneable {private String name;private Integer age;public Person(String strName, Integer iAge){this.name = strName;this.age = iAge;}@Overrideprotected Object clone() throws CloneNotSupportedException {// TODO Auto-generated method stubreturn super.clone();}}

 

public class Account implements Cloneable {private Person person;private Integer balance;public Account(Person p, Integer i){this.person = p;this.balance = i;}@Overrideprotected Object clone() throws CloneNotSupportedException {// TODO Auto-generated method stubAccount account =(Account) super.clone();account.person = (Person)this.person.clone();return account;}}

 

Note: The object. Clone method is protected (protected). This method is only visible in its subclass and package.

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.