Java基础之Cloneable对象的克隆

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

  • 1、实现Cloneable接口,(标记接口)
  • 2、重写Object类中的clone方法
    在这里插入图片描述
package com.vince;

/**
 * 对象需要具备克隆功能:
 * 1、实现Cloneable接口,(标记接口)
 * 2、重写Object类中的clone方法
 * @author vince
 * @description
 */
public class Cat implements Cloneable{
	private String name;
	private int age;
	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 Cat(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public Cat() {
		super();
	}
	//重写Object中的clone方法
	@Override
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + "]";
	}
	
}

Test

package com.vince;

/**
 * 对象需要具备克隆功能:
 * 1、实现Cloneable接口,(标记接口)
 * 2、重写Object类中的clone方法
 * @author vince
 * @description
 */
public class Cat implements Cloneable{
	private String name;
	private int age;
	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 Cat(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public Cat() {
		super();
	}
	//重写Object中的clone方法
	@Override
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + "]";
	}
	
}

结果
首先看下地址 输出这个是因为没写toString方法
他们地址不相等
在这里插入图片描述
最后结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/C_time/article/details/89366695
今日推荐