Java Object類中克隆clone()方法的使用
阿新 • • 發佈:2018-12-16
測試程式碼
package test04;
//
// protected Object clone()建立並返回物件一個副本。因為是protected型別的方法,只能在子類訪問
// 如果使用clone(),需要重寫此方法。
// 注意和Student s3=s1;區別,此為地址傳遞
// 用克隆方法時 :重寫此方法的類 必須實現Cloneable介面(這個介面是標記介面,告訴我們實現該介面的類可以實現物件的複製)
//
public class CloneDemo {
public static void main(String[] args) throws CloneNotSupportedException {
Student s1=new Student("zfliu",18);
System.out.println("S1的姓名:"+s1.getName()+",年齡:"+s1.getAge());
//使用clone方法實現克隆
Object obj=s1.clone();
Student s2=(Student)obj;
System.out.println("S2的姓名:"+s2.getName()+",年齡:"+s2.getAge());
//此處也可以實現複製,但是此種方法是將s1的地址給了s3,這是如果改變s3裡面的東西s1也會跟著變化,但是由於s2是克隆的s1,所以s2並不會被改變
Student s3=s1;
System.out.println("S3的姓名:"+s3.getName()+",年齡:"+s3.getAge());
s3.setAge(20);
s3.setName("liuzf");
System.out.println("S1的姓名:"+s1.getName()+",年齡:"+s1.getAge());
System.out.println("S2的姓名:"+s2.getName()+",年齡:"+s2.getAge());
System.out.println("S3的姓名:"+s3.getName()+",年齡:" +s3.getAge());
}
}
//此處實現Cloneable介面
class Student implements Cloneable{
private String name;
private int age;
public Student() {
}
public Student(String name,int age) {
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;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
輸出結果: