深拷贝实例(一个类中包含另一个类的对象)

来源:互联网 发布:qq酷双项淘宝客真的吗 编辑:程序博客网 时间:2024/06/18 05:47
import java.util.*;/** * 深拷贝 *  */public class test {    public static void main(String[] args){        String name = "张三";        int age = 15;        Address ads = new Address();        ads.setAddress("北京");        Student stu1 = new Student(name,age,ads);        Student stu2 = stu1.clone();        ads.setAddress("石家庄");        System.out.println("学生1的姓名:"+stu1.getName()+" 年龄是:"+stu1.getAge()+" 位置:"+stu1.getAds().getAddress());        System.out.println("学生2的姓名:"+stu2.getName()+" 年龄是:"+stu2.getAge()+" 位置:"+stu2.getAds().getAddress());    }}//地址类class Address implements Cloneable{    private String address;    public String getAddress() {        return address;    }    public void setAddress(String address) {        this.address = address;    }    @Override    public Object clone(){        Address address = null;        try {            address = (Address) super.clone();        } catch (CloneNotSupportedException e) {            e.printStackTrace();        }        return address;    }}//学生类class Student implements Cloneable{    private String name;    private int age;    private Address ads;    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;    }    public Address getAds() {        return ads;    }    public void setAds(Address ads) {        this.ads = ads;    }    public Student(String name, int age, Address ads){        this.name = name;        this.age = age;        this.ads = ads;    }    @Override    public Student clone(){        Student stu = null;        try {            stu = (Student) super.clone();        } catch (CloneNotSupportedException e) {            e.printStackTrace();        }        stu.ads = (Address) ads.clone();        return stu;    }}运行结果是:学生1的姓名:张三 年龄是:15 位置:石家庄学生2的姓名:张三 年龄是:15 位置:北京学生2进行了深拷贝, 所以位置没有发生变化。 

阅读全文
0 0
原创粉丝点击