Java 的浅拷贝和深拷贝

Java 的浅拷贝和深拷贝,第1张

class Money implements Cloneable{
    public double money = 99.9;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
class Person implements Cloneable {
    public int age = 10;
    public Money m = new Money();

    @Override
    protected Object clone() throws CloneNotSupportedException {
       Person tmp = (Person) super.clone();
        tmp.m = (Money) this.m.clone();
        return tmp;
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                '}';
    }
}

public class Test {
    public static void main(String[] args) throws CloneNotSupportedException {
        Person person1 = new Person();
        Person person2 = (Person) person1.clone();
        System.out.println(person1.age + " " + person2.age);
        person2.age = 20;
        System.out.println(person1.age + " " + person2.age);
        System.out.println("-------------------------");

        Person person3 = new Person();
        Person person4 = (Person) person3.clone();
        System.out.println(person3.m.money+" "+ person4.m.money);
        person3.m.money = 99;
        System.out.println(person3.m.money+" "+ person4.m.money);
        System.out.println("----------------------------");

        Person person5 = new Person();
        Person person6 = (Person) person5.clone();
        System.out.println(person5.m.money+" "+ person6.m.money);
        person5.m.money=11.11;
        System.out.println(person5.m.money+" "+ person6.m.money);

    }
}

  

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/923910.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存