java中克隆clone()的使用

protect Object clone() throws CloneNotSupportedException(克隆支持)

创建并返回此对象的副本。“复制”的精确含义可能取决于对象的类

对于任何的x表达式:x.clone!=x。只是将类“复制过来”并不需要重新new这里需要很多对象的时候提高了效率。


clone()方法位于java.util.Object。是protected的,使用的时候不能直接调用,需要重写。

重写的步骤:(javabean)

    1、声明Cloneable接口(贴标签技术)

    2、调用super.clone拿到一个对象,如果父类的clone实现没有问题的时候,则该对象的内存存储中,所有的父类定义的field有已经克隆好了,该类中的primitive(基本数据类型)行业不可变类型(String)引用也克隆好了,可变类型的引用都是浅copy。

    3、把浅copy的引用指向原型对象新的克隆体。

public class clone {
	public static void main(String[] args) {
		Person p1=new Person("jack",20);//浅拷贝
		
		Person p2=null;
		try {
			p2=(Person) p1.clone();//深拷贝
			System.out.println(p2);//Person name=jack, age=20
			p2.setName("Rose");
			p2.setAge(19);
			System.out.println(p2);//Person name=Rose, age=19
		} catch (CloneNotSupportedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
}

class Person implements Cloneable{
	private String name;
	private int age;
	public Person(){//如果要被外界所调用值必须写一个空参函数
		
	}
	public Person(String name,int age){
		this.name=name;
		this.age=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;
	}
	@Override
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
	@Override
	public String toString() {
		return "Person name=" + name + ", age=" + age ;
	}	
}



猜你喜欢

转载自blog.csdn.net/e286878553/article/details/80698487
今日推荐