1. 程式人生 > 其它 >Java常用類學習:Object類(clone方法new)

Java常用類學習:Object類(clone方法new)

Java常用類學習:Object類(clone方法new)

  • clone( )方法:

    • Object clone()方法用於建立並返回一個物件的拷貝;

    • clone方法是淺拷貝,只會拷貝引用地址,而不會將物件重新分配記憶體,相對應的深拷貝則會連引用的物件也重新建立;

  • 語法:

    • object.clone();

  • 引數:無

  • 返回值:

    • 返回一個物件的拷貝;

    • 由於Object本身沒有實現Cloneable介面,所以不重寫clone方法並且進行呼叫的話會發生CloneNotSupportedException異常;

  • 程式碼案例:


    /**
    * 測試類
    */
    public class Test implements Cloneable {

       //宣告變數
       String name;
       int age;

       public static void main(String[] args) {
           Test t=new Test();
           t.name="haha";
           t.age=11;

           //列印輸出
           System.out.println(t.age);//11
           System.out.println(t.name);//haha
           try {
               //建立t的拷貝
               Test t1=(Test) t.clone();
               //使用t1輸出變數
               System.out.println(t1.name);//haha
               System.out.println(t1.age);//11
          } catch (CloneNotSupportedException e) {
               e.printStackTrace();
          }

      }

    }