深克隆浅克隆

1. 深克隆浅克隆区别

深克隆:将对象依赖的示例也克隆了一份出来

浅克隆:只是克隆当前对象示例,对象所依赖的其他示例则不克隆

2. 代码示例

@Data
public class Teacher implements Cloneable {

    private String name;
    private int age;

    public Teacher(String name, int age){
        this.name = name;
        this.age = age;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

@Data
public class Student implements Cloneable {
    private String name;
    private int age;
    private Teacher teacher;

    public Student(String n, int a, Teacher t){
        name = n;
        age = a;
        teacher = t;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Student student = (Student) super.clone();
        // 若没有对teacher进行克隆,则是浅克隆,clone出来的student对象内的teacher实例相同,在内存中指向同一个对象
        teacher = (Teacher) teacher.clone();
        return student;
    }

    public static void main(String args[]) throws CloneNotSupportedException {
        Teacher t1 = new Teacher("老师1", 45);
        Student s1 = new Student("同学1", 15, t1);

        Student s2 = (Student) s1.clone();
        s2.setName("同学2");
        s2.setAge(18);
        s2.getTeacher().setName("新老师");

        System.out.println(s1);
        System.out.println(s2);
    }
}

3. 应用场景:暂时不知道

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值