Java对象克隆了解

  1.java接口中有一种空的接口叫标识接口,这种接口值起到标识做用。

  2.要实现java对象克隆须要用到Object类的

     protected Object clone() throws CloneNotSupportedException
    方法,这个方法为protected限定,在本包中,或者不一样包的子类中才能访问,而且抛出异常。

   3.若是要实现对象克隆首先被克隆的类必须实现Cloneable接口,若是没有实现这个接口,调用clone()方法会抛出

    CloneNotSupportedException异常。


   4.实现cloneable接口后,由于不能访问Object类中的clone方法,因此咱们必须重写clone方法

       在子类的clone()方法中调用父类的clone()方法

 

package com.clone;
class Cat implements Cloneable{
	private int age;
	private String name;
	public void setAge(int age) {
		this.age = age;
	}
	public int getAge() {
		return age;
	}
	public Cat(int age,String name)
	{
		
		this.age=age;
		this.name=name;
	}
	public String toString()
	{
		return "姓名:"+this.name+",年龄:"+this.age;
	}
	
	@Override
	protected Object clone() throws CloneNotSupportedException {
		// TODO Auto-generated method stub
		return super.clone();
	}
	
}
public class TestClone {

	public static void main(String[] args) {
		Cat cat1=new Cat(20,"小白");
		Cat cat2=null;
		try {
			cat2=(Cat)cat1.clone();
		} catch (CloneNotSupportedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(cat1);
		System.out.println(cat2);
		
		cat1.setAge(30);
		
		System.out.println(cat1);
		System.out.println(cat2);
		
		System.out.println(cat1==cat2);
	
	}

}

  

相关文章
相关标签/搜索