JAVA-克隆对象

定义

将一个对象复制一份,称为对象的克隆技术
在Object类中存在一个clone()方法:
protected Object clone() throws CloneNotSupportedException
如果某个类的对象想要被克隆,则对象所在的类必须实现Cloneable接口。此接口没有定义任何方法,是一个标记接口

步骤

1、实现Clonrable接口
2、重写Object类中的clone方法

示例

说明:创建被复制对象的类,实现Clonrable接口,并重写Object类中的clone方法

//实现Clonrable接口
public class Cat implements Cloneable {
    private String name;
    private int age;
    public Cat(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public Cat() {
        super();
        // TODO Auto-generated constructor stub
    }
    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;
    }
    @Override
    public String toString() {
        return "Cat [name=" + name + ", age=" + age + "]";
    }
    //重写Object中的clone方法
    @Override
    protected Object clone() throws CloneNotSupportedException {
        // TODO Auto-generated method stub
        return super.clone();
    }
}

说明:创建实现对象复制类

public class Test {
    public static void main(String[]args) {
        Cat cat=new Cat("喵喵小白",2);
        try {
            Cat newCat=(Cat)cat.clone();
            System.out.println("cat"+cat);
            System.out.println("newCat"+newCat);
        } catch (CloneNotSupportedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

运行结果:
catCat [name=喵喵小白, age=2]
newCatCat [name=喵喵小白, age=2]

猜你喜欢

转载自blog.csdn.net/weixin_34061042/article/details/91037318
今日推荐