java 类的深度复制

直接上代码。。。。。。。重写哪部分在代码里有

import java.util.*;

public class Main {
    public static void main(String args[]) {
       Person p1 = new Person("张三",12, "中国", "长沙");
       Person p2 = (Person) p1.clone();
       Person p3 = p1;
       p1.street = "杭州";
       p1.setName("李四");
       p1.getNameAge();
       //深度拷贝
        System.out.println("深度拷贝");
       p2.getNameAge();
       //直接赋值
        System.out.println("直接拷贝");
       p3.getNameAge();
    }
}

class Address{
    String country;
    String street;
}

class Person extends Address implements Cloneable{
    private String name;
    private int age;
    private Address add;
    Person(String _name, int _age,String _country, String _street){
        this.name = _name;
        this.age = _age;
        this.country = _country;
        this.street = _street;
    }
    void setName(String _name){
        this.name = _name;
    }
    void getNameAge(){
        System.out.println(this.name+" "+this.age+" "+this.country+" "+this.street);
    }
    @Override
    public Object clone(){
        Person per = null;
        try {
            per = (Person)super.clone();
        }catch (CloneNotSupportedException e){

        }
        return per;
    }
}

deepcopy

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值