浅克隆和深克隆的区别

参考:https://blog.csdn.net/jeffleo/article/details/76737560

Student类:
package day13.Demo;

public class Student implements Cloneable{
    private String name;
    private int age;
    private Cost cost;

    public Student(){

    }
    public Student(String name, int age, Cost cost) {
        super();
        this.name = name;
        this.age = age;
        this.cost = cost;
    }
    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 Cost getCost() {
        return cost;
    }
    public void setCost(Cost cost) {
        this.cost = cost;
    }
    public Student clone() throws CloneNotSupportedException {
         Student cloned = (Student) super.clone();
         cloned.cost = (Cost) cost.clone();  //这一步添上去说明是深克隆
                                                                //这一步省略说明是浅克隆
         return cloned;
    }
    @Override
    public String toString() {
        System.out.println("[name:" + this.getName()+ " age:"  + this.getAge()
                + " cost:" +this.getCost().getMoney()+"]");
        return "";
    }
}
Cost类:

package day13.Demo;

public class Cost implements Cloneable, Comparable<Cost>{
    private int money;

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    @Override
    public  Object clone() throws CloneNotSupportedException{
        return super.clone();
    }
}
测试类TestClone:
package day13;

import java.util.Arrays;

import day13.Demo.Cost;
import day13.Demo.Student;

public class TestClone {
    public static void main(String[] args) throws          
    CloneNotSupportedException {
        Cost cost = new Cost();
        cost.setMoney(1000);
        Student stu = new Student("徐子峰", 20, cost);
        //stu对象中基本数据类型的hashcode值
        System.out.println(stu.hashCode()); 
         //stu对象中引用类型Cost的hashcode值
        System.out.println(stu.getCost().hashCode());

        System.out.println(stu.toString());


//测试浅克隆后,stu对象中改变引用类型Cost中的值会引起的变化
    cost.setMoney(2000);


        Student stu1 = (Student)stu.clone();
        //stu对象中基本数据类型克隆后的hashcode值
        System.out.println(stu1.hashCode());
        //stu对象中引用类型Cost克隆后的hashcode值
        System.out.println(stu1.getCost().hashCode());

        System.out.println(stu1.toString());
        System.out.println(stu.toString());



    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值