浅拷贝与深拷贝

来源:互联网 发布:双立人珐琅铸铁锅 知乎 编辑:程序博客网 时间:2024/06/09 22:24

浅拷贝与深拷贝,就是地址之间的“捆绑”,而且它涉及到栈内存和堆内存的储存关系;还是用代码和简图来说明问题吧!

   public class Client {

           public static void main(String[] rags ) {

                   MyDate  d = new  MyDate(1995,4,22);

                   Person  p = new  Person("Jack",d);

                  System.out.println("P:"+p.toString())  //Jack,1995年4月22日  

                  Person p3=new Person(p);  //引用赋值必“捆绑”,即地址之间“赋值”

                    p.setName("Tom");

                    p.getBirth().setYear(2000);

                    System.out.println("P:"+p.toString())  //Tom,2000年4月22日

                    System.out.println("P3:"+p.toString())  //Jack,2000年4月22日

            }

}


public class MyDate {

          private int year;

          private int month;

          private int day;

        public MyDate(int year,int month,int day)  {
            this.year=year;
            this.month=month;
            this.day=day;
        } 

        public MyDate()  {
            this(1970,1,1);
        }

       public MyDate (MyDate d)   {

            this(d.year,d.month,d.day);

        }

       public void setYear(int year)  {
            this.year = year;
       }
        public String toString(){
             return year+"年"+month+"月"+day+"日";
        }
}

  public class Person  {
          private String name;
          private MyDate birth;

         public Person(String name,MyDate birth){
           this.name = name;
         //this.birth = birth;//引用赋值必捆绑----出现浅拷贝
   
        //深拷贝的本质就是把"引用赋值" 变成 "基本数据类型或String类型赋值"
           this.birth = new MyDate(birth);
         }

        public Person(){
           this("NoName",null);
       }
        public Person( Person p ){
           this(p.name, p.birth);
      }
 
        public void setName(String name){
           this.name = name;
       }
        public MyDate getBirth(){
            return birth;
       }
        public String toString(){
            return name+","+birth.toString();
     }
 
}


拷贝分析图:


 















0 0
原创粉丝点击