java中克隆对象

克隆对象

package com.company;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.sql.*;
import java.util.zip.DataFormatException;


class Student implements Cloneable {
    String name;
    int age;

    public Student clone() throws CloneNotSupportedException
    {
        Student stu=(Student)super.clone();
        return stu;
    }


    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}


public class Main {

    public static void main(String[] args) throws InterruptedException, ParseException, CloneNotSupportedException {

        Student stu = new Student("waifei", 18);
        Student stu1=stu;
        stu1.setName("ha");
        Student clone=stu.clone();
        clone.setName("clone");
        System.out.println(stu.getName());
        System.out.println(clone.getName());
    }
}

如果用等号去接受引用类型的对象时,改变一个对象的数据,会影响到原来的对象。
所以为了实现真的两个隔离的对象,可以通过克隆的方式去创建
用克隆的话需要实现Cloneable接口,然后重写父类的clone方法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值