1.要实现某一类型对象(浅表)复制,则此类型必须满足以下条件:
(1):实现Cloneable这个空接口,
(2):重写Object下clone()方法。
2.示例:package com.pinus.exercise; import java.sql.Date; /** * 实现对象复制必须实现Cloneable这个空接口 */ public class Person implements Cloneable { private int age; private String name; private String sex; private Date birth; /** * 重写Object类中clone方法,实现对象浅表复制 */ public Person clone() { try { return (Person) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); throw new RuntimeException(e); } } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public String toString() { return "Person [name=" + name + ", sex=" + sex + ", birth=" + birth + "]"; } }
3.分析
super.clone():此方法有默认行为,即先复制父类中成员,再复制本类中成员
复制层次:利用super.clone()仅为浅层复制,可以让此类型实现序列化接口从而实现深层复制