API中的Object之clone方法和finalize方法
(1)protected void finalize( ):当垃圾回收器确定不存在该对象的更多引用时,由对象的垃圾回收器调用此方法。主要用于垃圾回收,但是什么回收,不确定。
(2)protected Object clone( ):创建并返回一个此对象的副本。
重写该方法: 自动生成的版本就行。
Cloneable:此类实现了Cloneable 接口,以指示Object.clone()方法可以合法的,对该实例进行按字段复制。
这个接口没有方法,仅仅表示的是一个标记接口,告诉我们 实现该接口就可以实现对象的复制了。
(3)举例子:
package cn.itcast_04;
//实现该标记接口
public class Student implements Cloneable {
private String name;
private int age;
public Student() {
super();
}
public Student(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
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
**********************************************************
public class StudentDemo {
public static void main(String[] args) throws CloneNotSupportedException {
// 创建类的对象
Student s = new Student();
s.setName("cmm");
s.setAge(26);
// 实现对象的复制
Object obj = s.clone();
// 对象的转型
Student s2 = (Student)obj;
System.out.println("name:"+s.getName()+", age:"+s.getAge());
System.out.println("name:"+s2.getName()+", age:"+s2.getAge());
System.out.println("-------------");
// 以前的做法:
Student s3 = s;
s3.setName("cmm2");
s3.setAge(36);
// 其实是有区别的。克隆做法:两个一模一样的克隆!
System.out.println("name:"+s.getName()+", age:"+s.getAge());
System.out.println("name:"+s2.getName()+", age:"+s2.getAge());
System.out.println("name:"+s3.getName()+", age:"+s3.getAge());
}
}