您的位置:首页 > 移动开发 > Objective-C

常见对象_Object类的finalize()方法和clone()方法

2016-11-01 23:35 429 查看
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();
}
}


package cn.itcast_04;

/*
* protected void finalize():当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。用于垃圾有回收,但是什么时候回收不确定。
* protected Object clone():创建并返回此对象的一个副本。
* A:重写该方法
*
* Cloneable:此类实现了 Cloneable 接口,以指示 Object.clone() 方法可以合法地对该类实例进行按字段复制。
* 这个接口是标记接口,告诉我们实现该接口的类就可以实现对象复制了。
*/
public class StudentDemo {
public static void main(String[] args) throws CloneNotSupportedException {
//创建学生对象
Student s = new Student("ss",22);

//克隆学生对象
Object obj = s.clone();
Student s2 = (Student)obj;
System.out.println("-----------------------");

System.out.println(s.getName()+"---"+s.getAge());
System.out.println(s2.getName()+"---"+s2.getAge());

//以前做法
Student s3 = s;
System.out.println(s3.getName()+"---"+s3.getAge());
System.out.println("-----------------------");

//其实有区别的(克隆当前对象,执行后将复制一份当前对象)
s3.setName("sb");
s3.setAge(44);
System.out.println(s.getName()+"---"+s.getAge());
System.out.println(s2.getName()+"---"+s2.getAge());
System.out.println(s3.getName()+"---"+s3.getAge());

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: