Talking about clone() method to clone objects

1. What is clone

  The clone() method is a method in the Object class, use this method to clone an object. In the actual programming process, we often encounter this situation: there is an object object1, and at a certain moment object1 contains some valid values. At this time, a new object object2 that is exactly the same as object1 may be required, and thereafter Any changes to object2 will not affect the value in object1, that is, object1 and object2 are two independent objects, but the initial value of object2 is determined by object1. In the Java language, simple assignment statements cannot meet this requirement. Although there are many ways to meet this demand, the clone() method is the simplest and most efficient method.

2. Clone has deep clone and shallow clone, so what is the difference between deep clone and shallow clone?

     Shallow clone: ​​only the attributes of basic data types can be cloned;

     Deep clone: ​​Basic data type and reference data type attributes can be cloned.

     Deep clone implementation:

            ① Both the cloned class and the class corresponding to the referenced attribute implement Cloneable to override the clone method;

            ②Add the reference type attribute assignment code in the clone method of the cloned class, such as employee.address = address.clone();

public class TestClone {
    //1. Clone is divided into shallow clone and deep clone
    // Shallow clone: ​​only attributes of basic data types can be cloned
    // Deep clone: ​​Both basic types and reference type attributes can be cloned
    //2. Implementation method of deep clone:
    // ① Both the cloned class and the class corresponding to the application attribute implements Cloneable to override the clone method
    // ②Add the reference type attribute assignment code in the clone method of the cloned class, such as employee.address = address.clone();

    public static void main(String[] args) {
        System.out.println("before cloning");
        Address address = new Address("China", "Hebei Province", "Cangzhou City");
        Employee employee1 = new Employee("马苏", 32, address);
        System.out.println("Employee 1 information ==> "+ employee1);
        //Before cloning
        //Employee 1 information ==> Employee{name='Ma Su', age=32, address=Address{state='China', province='Hebei Province', city='Cangzhou City'}}
        Employee employee2 = employee1.clone();
        employee2.setAge(23);
        employee2.setName("jack");
        employee2.getAddress().setProvince("上海");
        employee2.getAddress().setCity("Huangpu District->Shanghai Bund");
        System.out.println("After cloning");
        System.out.println("Employee 1 information ==> "+ employee1);
        //After cloning
        //Employee 1 information ==> Employee{name='Ma Su', age=32, address=Address{state='China', province='Hebei Province', city='Cangzhou City'}}
        //Employee 2 information ==> Employee{name='jack', age=23, address=Address{state='China', province='Shanghai', city='Huangpu District->Shanghai Bund'}}
        System.out.println("Employee 2 information ==> "+ employee2);

    }

}

    class Address implements Cloneable{
        private String state;
        private String province;
        private String city;

        public Address(String state, String province, String city) {
            this.state = state;
            this.province = province;
            this.city = city;
        }

        public String getState() {
            return state;
        }

        public void setState(String state) {
            this.state = state;
        }

        public String getProvince() {
            return province;
        }

        public void setProvince(String province) {
            this.province = province;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        @Override
        public String toString() {
            return "Address{" +
                    "state='" + state + '\'' +
                    ", province='" + province + '\'' +
                    ", city='" + city + '\'' +
                    '}';
        }

        @Override
        protected Address clone()  {
            Address address = null;
            try {
                address = (Address)super.clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace ();
            }
            return address;
        }
    }

    class Employee implements Cloneable {

        private String name;
        private int age;
        private Address address;

        public Employee(String name, int age, Address address) {
            this.name = name;
            this.age = age;
            this.address = address;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public Address getAddress() {
            return address;
        }

        public void setAddress(Address address) {
            this.address = address;
        }

        @Override
        public String toString() {
            return "Employee{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", address=" + address +
                    '}';
        }

        @Override
        protected Employee clone() {
            Employee employee = null;
            try {
                employee = (Employee) super.clone();
                employee.address = address.clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace ();
            }
            return employee;
         }
    }

Guess you like

Origin blog.csdn.net/qq_37451441/article/details/109286977