clone
protected Object clone() throws CloneNotSupportedException 一般情况下,要clone方法需要抛出异常创建并返回此对象的一个副本x.clone() != x 也就是说是不同的对象,复制的对象与原来的对象是一个不同的对象x.clone().getClass() == x.getClass() 说明是同一个类Cloneable接口 在clone方法所在类中需要实现这个接口,因为这个接口是复制的标志接口记住: 这个接口没有构造方法与成员方法 package cn.itcast_04; public class Student4 implements Cloneable { private String name; private int age; public Student4() { super(); } public Student4(String name, int age) { //调用是Object构造方法 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; } //重写clone()方法重写 @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }package cn.itcast_04; /* *protected void finalize();当垃圾回收器确定不存在对象有更多引用时候,垃圾回收器调用此方法 *但是什么时候调用该方法不知道 * *proected Object clone();创建并且返回该对象的副本 * A:重写该方法; * * Cloneabel;此类实现了Cloneable 接口,以指示Object.clone()方法对对象复制 换句话说,只有实现该接口,才能复制对象 Cloneable 是标志接口,里面没有方法,只有继承该方法才能克隆对象 */ public class StudentDemo4 { public static void main(String[] args) throws CloneNotSupportedException { //创建学生对象 Student4 s = new Student4(); s.setName("liqingxiang"); s.setAge(24); Object obj = s.clone(); Student4 s2 = (Student4)obj; System.out.println("name:" + s.getName() + ", age:" +s.getAge()); System.out.println("name:" + s2.getName() + ", age:" +s2.getAge()); System.out.println("=============="); //s对象改变,但是s2对象属性没变,因此他们是两个不同的对象 s.setAge(29); s.setName("xiaoming"); System.out.println("name:" + s2.getName() + ", age:" +s2.getAge()); } }
转载于:https://www.cnblogs.com/yu-zhi/p/9527155.html