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

来源:互联网 发布:linux进去文件夹 编辑:程序博客网 时间:2024/06/10 06:15


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;}@Overrideprotected 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());}}


0 0