Java API 之Cloneable

  • 1.将一个对象复制一份,称为对象的克隆技术
  • 2.在Object类中存在一个clone()的方法;
  • 3.protected Object clone() throws CloneNotSupportedException
  • 如果某个类的对象想要被克隆,则对象所在的类必须实现Cloneable接口。此接口没有任何定义
  • 方法,是一个标记接口。
  • 步骤
  • 1.实现Cloneable接口(标记接口,就是告诉虚拟机)
  • 2.重写Object类中的clone方法
package com.vince;
/**
 * 1.将一个对象复制一份,称为对象的克隆技术
 * 2.在Object类中存在一个clone()的方法;
 * 3.protected Object clone() throws CloneNotSupportedException
 * 如果某个类的对象想要被克隆,则对象所在的类必须实现Cloneable接口。此接口没有任何定义
 * 方法,是一个标记接口。
 * 步骤
 * 1.实现Cloneable接口(标记接口,就是告诉虚拟机)
 * 2.重写Object类中的clone方法
 * 
 *
 */
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() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Cat(String name, int age) {
		super();
		this.name = name;
		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();
	}
	
}

猜你喜欢

转载自blog.csdn.net/weixin_44117272/article/details/89516016