How Java implements deep copy

Source: Internet
Author: User

Protected the subtle rules of the domain (or method)

protectedThe domain (or method) is visible to all classes within the package (including, of course, subclasses), then the subclass can gain access to the superclass protected domain (or method), but if the subclass and superclass are not under the same package, the protected domain (or method) of the superclass object cannot be accessed. That is, not under a package, the subclass cannot get the parent class's protected domain (or method) through a reference to a parent class object, as shown in the following test.

package protect2;publicclass P{    protectedint a;    publicP(){}    publicP(int a){        this.a = a;    }    protectedvoidfun(){        System.out.println("父类protected方法");    }}
Package Protect2; Public classprotectedtest { PublicString s; Public protectedtest(String s) { This.s= S; } P AP =New P(Ten);void Foo() {AP. Fun(); System. out.println("Ap.a"+ AP.a); } Public Static void Main(string[] args) {Protectedtest test =New protectedtest("ABCdef"); Test.Foo(); System. out.println(Test.s); }}
Package Protect;import Protect2. P;classCextendsp{ Public intb Public C(intAintb) {Super(a); This.b= b; } Public void Afun() {P pp =New P(Ten); System. out.println("C.a="+ a); System. out.println("P.a="+ pp.a);//error:the field P.a is not visiblePp. Fun();//error:the Method Fun () from the type P was not visible}
Shallow copy and deep copy

The object class is ignorant of the domain of its own specific subclass, and Object the class's clone methods simply copy each domain. There is no problem with numeric or basic types, but if you include reference objects in the object, the contents of those objects are not copied themselves, the result of the copy is that the original object and the Copy object refer to the same reference object (generally, the verb "reference" can be understood as "management", that is, pointing to the same memory).

Shallow copy satisfies:

    1. x.clone() != xFor true ,
    2. x.clone().getClass() == x.getClass()For true ,
    3. ((x.clone().field1 ) == (x. field1))&& … &&((x.clone().fieldN )==(x. fieldN))Also for true .

If the reference object that the original object is co-referencing (managed, pointed) with a shallow copy object is immutable, there will be no problem, such as that the reference object is a string class object, or the reference object does not change in its life cycle, specifically, there is no way to change it in the class that manages it. Nor does it return the method that it refers to (the method by which it shares its management rights).

If the reference object managed by the original object is mutable, it is necessary to redefine the clone method to achieve a deep copy. To determine the following two points for each of the classes involved:

    • Whether the default clone method satisfies the requirement.
    • Whether the default clone method can be resolved by invoking the Clone method of a mutable reference object.

For each of the classes involved, a deep copy is to satisfy:

    1. x.clone() != xFor true ,
    2. x.clone().getClass() == x.getClass()For true ,
    3. x.clone().equals(x)Also true , of course, the Equals method is so rewritten.

ObjectThe methods in the class are clone declared to protected prevent the occurrence of subclasses and superclass that are not under the same package as mentioned at the beginning of the article, to be declared to clone implement a public deep copy:

import java.util.Date; Public classEqualst { Public Static void Main(string[] args)throwsclonenotsupportedexception {Date Hireday =NewDate (); Employee e1 =New Employee("Tommy",Ten,"9998", Hireday); Employee e2 =New Employee("Tommy",Ten,"9998", Hireday); System. out.println(E1.equals(E2)); System. out.println(e1 = = E2); Employee E3 = (employee) E1.Clone(); System. out.println(E1.equals(E3)); }}//cloneable is a tag interface, there is no method inside the interface. classEmployeeImplementscloneable {String name;intAge    String salary; Date Hireday; Public Employee(String name,intAge, String salary, Date hireday) {Super(); This.name= name; This. Age= age; This.Salary= salary; This.Hireday= Hireday; }@Override     Public Boolean equals(Object Otherobject) {if( This= = Otherobject)return true;if(Otherobject = =NULL)return false;if(! (OtherobjectinstanceofEmployee))return false; Employee other = (employee) Otherobject;returnName.equals(Other.name) && age = = Other. Age&& salary.equals(Other.Salary) && Hireday.equals(Other.Hireday); }@Override    protectedObjectClone()throwsclonenotsupportedexception {//Call Object.clone ()Employee cloned = (employee)Super.Clone();//Call mutable fieldsCloned.Hireday= (Date) hireday.Clone();returnCloned }}output:truefalsetrue
// JDK中Date类的克隆方法publicclone() {        null;        try {            d = (Date)super.clone();            ifnull) {                d.cdate = (BaseCalendar.Date) cdate.clone();            }        catch// Won't happen        return d;    }

(-???? ??? -)(-???? ??? -)(-???? ??? -) errors or deficiencies, welcome communication; Like on top, don't restrain. (???????)???????

How Java implements deep copy

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.