浅复制:只复制基本数据类型,引用类型仍然共用一个
深复制:不管是什么统统一起复制
定义一个学生对象,实现克隆的接口
//测试
public class Test {
public static void main(String[] args) {
Student s1 = new Student (25,"张三", new Address(5,"天府广场"));
//调用克隆的方法,深度复制
Student s2=s1.Clone();
//Student [age=25, name=李, address=Address [no=5, add=天府广场]]
System.out.println(s2);
}
public class Student implements Cloneable {
int age;
String name;
Address address;
@Override
public String toString() {
return "Student [age=" + age + ", name=" + name + ", address=" + address + "]";
}
public Student(int age, String name, Address address) {
super();
this.age = age;
this.name = name;
this.address = address;
}
//重写Clone方法
public Student Clone() {
Student s=null;
try {
s=(Student)super.clone();
s.address=this.address.Clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
定义一个地址对象,也要实现克隆接口,待会儿复制学生对象的时候一起复制
public class Address implements Cloneable{
int no;
String add;
public Address Clone() {
Address a=null;
try {
a=(Address)super.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return a;
}
public Address(int no, String add) {
super();
this.no = no;
this.add = add;
}
@Override
public String toString() {
return "Address [no=" + no + ", add=" + add + "]";
}