5、对象的克隆
将一个对象复制一份,称为对象的克隆技术。
在Object类的存在一个clone()的方法;
protected Object clone()throws CloneNotSupportedException
如果某个类的对象要想被克隆,则对象的类必须实现Cloneable接口。次接口没有定义任何方法,是一个标记接口。对象克隆的应用场景是需要建立一组粒度重复使用的对象时,使用克隆方式可能比直接创建对象的效率要高好多。
public class ConesDome {
public static void main(String[] args) {
// TODO Auto-generated method stub
Cat cat=new Cat(24,"喵喵");
try {
Cat newcat=(Cat)cat.clone();
System.out.println("cat="+cat);
System.out.println("ne wat="+newcat);
}catch(CloneNotSupportedException e){
e.printStackTrace();
}
}
}
/*
* 1、对象需要具备克隆功能
* 2、实现Cloneable接口
* 3、重写Object类中的clone方法
*
*/
public class Cat implements Cloneable{
private int age;
private String name;
public Cat() {
super();
// TODO Auto-generated constructor stub
}
public Cat(int age, String name) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//重写Object中的clone方法
protected Object clone() throws CloneNotSupportedException{
return super.clone();
}
@Override
public String toString() {
return "Cat [age=" + age + ", name=" + name + "]";
}
}