通过实现Cloneable接口来克隆对象。
public class Sheep implements Cloneable {
private String name;
private int weight;
public Sheep(String name, int weight) {
this.name= name;
this.weight= weight;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
// 创造一只羊
Sheep sheep = new Sheep("Dolly", 20);
// 克隆羊
Sheep dolly = (Sheep) sheep.clone(); //dolly.nameis "Dolly" anddolly.weightis 20