在编程过程中有的时候往往需要创建多个重复的对象,例如游戏 飞机大战中发射的子弹,这些大量且重复的对象,如果一个一个去创建的话,会非常的麻烦,此时我们就需要引入克隆技术
Cloneable接口
将一个对象复制一份,称为对象的克隆技术。
在object类中存在一个clone()方法:protected Object clone() throws CloneNotSupportedException如果某个类的对象要想被克隆,则对象所在的类必须实现Cloneable接口。此接口没有定义任何方法是一个标记接口
package com.chen;
/**
* 对象需要具备克隆功能
* 1、实现Cloneable接口,(标记接口)
* 2、重写Object类中的clone方法
* @author 11010
*
*/
public class Cat implements Cloneable{
private String name;
private int age;
public Cat() {
super();
// TODO Auto-generated constructor stub
}
public Cat(String name, int age) {
super();
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
public String toString() {
return "Cat [name=" + name + ", age=" + age + "]";
}
//重写Object中的clone方法
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
}
要注意的是需要在最后重写clone()
package com.chen;
public class Teset {
public static void main(String[] args) {
Cat cat = new Cat("咪咪",1);
try {
Cat newcat = (Cat)cat.clone();
System.out.println(cat);
System.out.println(newcat);
System.out.println(cat==newcat);
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这样,就可以在创建对象之后,直接对对象进行克隆,如果想克隆多个对象则只需要通过循环就能实现,其效率大大的提高。
值得注意的是:虽然克隆的对象内容和原有的对象一样,但本质上他们还是两个不同的对象,他们的地址不同;
以下是代码的运行结果: