Java中Clone方法
一. Clone的原理:
將現有的物件克隆一份,包括給現有物件屬性所賦的值,形成一個新的物件,相當於在記憶體中將現有物件拷貝一份,並重新分配記憶體空間,拷貝後的物件和現有的物件相當於物理隔離了,操作克隆物件不會影響原來物件。
二. Clone的前提:
1. 要克隆的類實現Cloneable介面;
2. 在克隆類中重寫clone()方法,
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
三. 程式碼實現:
User.java:
public class User implements Cloneable{
private String name;
private int 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
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
UserClone.java:
public class UserClone {
/**
* @param args
* @throws CloneNotSupportedException
*/
public static void main(String[] args) throws CloneNotSupportedException {
User user = new User();
user.setName("測試1");
user.setAge(18);
User user2 = (User)user.clone();
user2.setName("測試2");
user2.setAge(111);
System.out.println(user.getName()+user.getAge());
System.out.println(user2.getName()+user2.getAge());
}
}