天天看點

java 學習 -深層拷貝 淺層拷貝 暑假第九天

/*java 對象的克隆     實作Cloneable接口 但是這個接口中沒有任何的 抽象方法 隻是為了

告訴 java 虛拟機這個對象可以被複制  然後我們在類中重寫clone方法  這個方法從object定義

在子類中調用 super.clone()來克隆   因為object類的clone是protected權限不能再外部通路 、

當我們傳遞的對象引用的時候 不想改變原來的對象值 這時候我們就需要一個臨時的副本

clone方法就實作了這一點

1.淺層拷貝  沒有引用成員

2.深層拷貝  将引用成員一起拷貝了 拷貝後修改不會引起原來資料的改變

*/

//例子:

class Student   implements Cloneable

 String name;

 int age;

 Professior p;

 Student(int age,String name,Professior p)

 {

  this.age=age;

  this.name=name;

  this.p=p;

 }

 public  Object clone()  //重載克隆函數   在克隆函數中調用内部引用成員的克隆函數 傳回拷貝

 { Object o=null;

 try

  {

 o=super.clone();  //因為會跑出異常是以我們要進行異常捕獲

  }

 catch(CloneNotSupportedException e)

  {

   System.out.println("NOT SUPPPORTED CLONE");

  this.p=(Professior)p.clone();  //要進行強制轉換一下

 return o;

}

class Professior  implements  Cloneable  //實作一個沒有abstract方法的接口是為了告訴java編譯器可以被克隆

{

 Professior(int age,String name)

public  Object clone()  //重載克隆函數因為 基類的是 protected權限的

{ Object o=null;

class Test  //主函數

 void change(Student st)

 public static void main(String []args)

  Professior pro=new Professior(40,"laowang");

  Student st=new Student(20,"xiaoyue",pro);

  Student st2=(Student)st.clone();  //克隆Student這個類的此對象

  st2.age=33;//對拷貝進行指派

  System.out.println(st.age);  //輸出原來的值

  st2.p.age=66; //對教授進行指派

  System.out.println(st.p.age);