根據一個現有對象克隆出多個對象,這叫作原型模式。Java中的Cloneable接口定義了對象的克隆,它是一個聲明式接口,沒有定義任何抽象方法。Cloneable接口存在的惟一意義是:告知Java虛擬機,能夠在該對象上調用Clone()方法。實際上,Clone()方法定義在Object類中,而且它是一個protected方法,以下所示:ide
protected native Object clone() throws CloneNotSupportedException;
複製代碼
當對一個沒有實現Cloneable接口的類的實例上調用clone()方法時,將會拋出CloneNotSupportedException。也是說是,若是但願調用對象的clone()方法,咱們須要:this
以下所示:spa
class Student {
private String name;
private int age;
@Override
public Student clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return (Student) super.clone();
}
Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
複製代碼
類Student實現了Cloneable接口並重寫了clone()方法,同時修改訪問修飾符爲public。在重寫後的方法體中,調用Object類的clone()方法。Object類的clone()方法,實現的是淺度克隆,所謂的淺度克隆是指,只克隆值類型屬性,不可隆引用類型屬性,而是將克隆對象的引用屬性指向原對象的對應屬性。以下所示:code
public static void main(String[] args) throws CloneNotSupportedException {
Student1 student = new Student1("hhx", 12);
Student1 student2 = student.clone();
System.out.println(student.getAge() == student2.getAge()); // true
System.out.println(student.getName() == student2.getName()); // true
}
複製代碼
若是但願實現深度克隆,也就是既克隆值類型屬性,也克隆引用類型屬性,則必須重寫clone()方法的內容,以下所示:對象
class Student2 {
private String name;
private int age;
@Override
public Student2 clone() throws CloneNotSupportedException {
Student2 student = new Student2(name, age);
student.name = new String(name);
return student;
}
Student2(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
複製代碼
此時,有:接口
public static void main(String[] args) throws CloneNotSupportedException {
Student2 student = new Student2("hhx", 12);
Student2 student2 = student.clone();
System.out.println(student.getAge() == student2.getAge()); // true
System.out.println(student.getName() == student2.getName()); // false
}
複製代碼
以上就是Java中的克隆機制,最後再總結一下Java中方法重載與重寫的區別:方法重載做用於同一個類中的不一樣方法之間,要求方法的名稱相同,方法的參數不徹底相同;而方法重寫用於父類和子類之間,要求名稱和參數徹底相同,而方法的返回類型和拋出的異常類型必須和原方法相同或是子類,而方法的訪問修飾符只能增長不能減少。get