浅拷贝和深拷贝

class Money{
    public double m = 12.5;
}
class Add implements Cloneable{
    public Money money = new Money();
    public int age;
    public String name;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Add a = new Add();
        Add b = (Add)a.clone();
    }
}//这里是一个浅拷贝

以上方法是一个浅拷贝,若要拷贝需要具备一个条件,第一就是要拷贝的这个类要实现Clonable这个接口代表该类可以被拷贝,此时所进行的拷贝并不能将该对象完全拷贝,拷贝出来的moeny和this的moeny都指向同一个存储位置,如果要想修改moeny的值,无论是修改拷贝出来的还是原本的都会导致两个对象的moeny发生同步的变化

class M implements Cloneable{
    public double price = 12.5;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
class Student implements Cloneable{
    String name;
    int age;
    M m = new M();

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Student student = (Student) super.clone();
        student.m= (M)student.m.clone();
        return student;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", m=" + m.price +
                '}';
    }

    public Student(int age, String name) {

        this.age = age;
        this.name = name;

    }
}
public class Main {
    public static void main(String[] args) throws CloneNotSupportedException{
        Scanner scanner = new Scanner(System.in);
        Student student1 = new Student(15,"刘杰");
        Student student2 = (Student) student1.clone();
        student2.m.price = 100.0;
        System.out.println(student1.toString());
        System.out.println(student2.toString());
    }
}

以上就是一个深拷贝,此时再此将student1进行拷贝,拷贝之后的price指向一个新的存储位置,两个price就是相互独立的了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值