您的位置:首页 > 编程语言 > Java开发

java之clone(克隆)方法

2018-03-14 19:44 225 查看
    clone方法是对对象的复制,赋值的对象有自己的内存空间,往往是独立的。
    clone是object中的一个方法,此方法未实现,是native方法,即本地方法(可以调用底层操作系统的方法),在调用本地方法创建对象时,比直接new创建对象效率要高。

    在使用clone方法创建对象时,要实现Cloneable接口,此接口没有任何方法,只是一个标识接口。

    例子:
//student类,重写clone方法
public class Student implements Cloneable {//Student实现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;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Object clone() throws CloneNotSupportedException {//将protected转变为public
// TODO Auto-generated method stub
Student s=null;
s=(Student) super.clone();
return s;
}

}
//测试克隆方法
public class TestClone {
public static void main(String[] args) throws CloneNotSupportedException {
Student s=new Student("jim",18);
Student stu=(Student) s.clone();
s.setName("mary");
System.out.println(s.getName()+" "+stu.getName());
}

}
程序运行结果:mary jim
结果分析:打印的s与stu不同,则说明克隆复制成功,s与stu系统分配的内存空间不同。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: