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系统分配的内存空间不同。
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系统分配的内存空间不同。
相关文章推荐
- Java中Object类的clone()(克隆)方法
- Java clone克隆方法 --深拷贝--浅拷贝 --原型模型
- (转)Java克隆方法的研究(clone)
- 方法object面试题分析:7JAVA中Object的clone方法详解-克隆-深克隆
- java克隆对象clone()的使用方法和作用
- 浅析Java中clone()方法浅克隆与深度克隆
- java中的clone()方法的研究---(2)浅克隆和深克隆
- Java 深度克隆 clone()方法重写 equals()方法的重写
- Java案例:使用clone()方法克隆对象
- Object.clone()方法引申出的浅克隆、深克隆、java原型模式的实现、不可变类的实现
- java中equals和==之间的区别?clone方法的作用,及其为什么要使用clone方法?如何使用clone复制对象?以及深克隆浅克隆
- Java 深度克隆 clone()方法重写 equals()方法的重写
- Java克隆方法的研究(clone)
- java 深克隆clone对象或容器的另一种方法
- 【java】克隆方法clone()和相等方法equals()的重写
- JAVA克隆详解以及clone方法使用
- Java 深度克隆 clone()方法重写 equals()方法的重写
- Java 基础数据类型 和 深度克隆对象的2种方法(实现Cloneable接口或者实现对象序列化)
- 面试题分析:7JAVA中Object的clone方法详解-克隆-深克隆
- java clone方法使用详解