Object_clone

clonenode

  • protected Object clone() throws CloneNotSupportedException
    • 通常狀況下,要clone方法須要拋出異常
    • 建立並返回此對象的一個副本
    • x.clone() != x
      • 也就是說是不一樣的對象,複製的對象與原來的對象是一個不一樣的對象
    • x.clone().getClass() == x.getClass()
      • 說明是同一個類
  • Cloneable接口
    • 在clone方法所在類中須要實現這個接口,由於這個接口是複製的標誌接口
    • 記住: 這個接口沒有構造方法與成員方法
package cn.itcast_04; public class Student4 implements Cloneable { private String name; private int age; public Student4() { super(); } public Student4(String name, int age) {
     //調用是Object構造方法    
super(); this.name = name; this.age = age; } 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; } //重寫clone()方法重寫 @Override protected Object clone() throws CloneNotSupportedException { return super
.clone(); } }







 

package cn.itcast_04; /* *protected void finalize();當垃圾回收器肯定不存在對象有更多引用時候,垃圾回收器調用此方法 *可是何時調用該方法不知道 * *proected Object clone();建立而且返回該對象的副本 * A:重寫該方法; * * Cloneabel;此類實現了Cloneable 接口,以指示Object.clone()方法對對象複製 換句話說,只有實現該接口,才能複製對象 Cloneable 是標誌接口,裏面沒有方法,只有繼承該方法才能克隆對象 */
 
public class StudentDemo4 { public static void main(String[] args) throws CloneNotSupportedException { //建立學生對象
        Student4 s = new Student4(); s.setName("liqingxiang"); s.setAge(24); Object obj = s.clone(); Student4 s2 = (Student4)obj; System.out.println("name:" + s.getName() + ",  age:" +s.getAge()); System.out.println("name:" + s2.getName() + ",  age:" +s2.getAge()); System.out.println("=============="); //s對象改變,可是s2對象屬性沒變,所以他們是兩個不一樣的對象
        s.setAge(29); s.setName("xiaoming"); System.out.println("name:" + s2.getName() + ",  age:" +s2.getAge()); } }
本站公眾號
   歡迎關注本站公眾號,獲取更多信息