面试题分析:7JAVA中Object的clone方法详解-克隆-深克隆

package com.luzhiming.test_14;

/**
 * @author strungle E-mail: [email protected]
 * @version 创建时间:2013-6-23 下午6:44:06
 * 
 */
public class Page14Number15 {


	public static void main(String[] args) throws Exception {

		Teacher teacherWang = new Teacher(1,"张老师");
		
		Student p1 = new Student(1, "zhangsan");
		p1.setTeacher(teacherWang);
		
		Student p2 = (Student)p1.clone();
		p2.getTeacher().setName("李老师");
		
		
		
		System.out.println(p1.getTeacher().getName());
		System.out.println(p2.getTeacher().getName());
	}

}

class Student implements Cloneable {
	int age;
	String name;
	Teacher teacher;
	
	public Teacher getTeacher() {
		return teacher;
	}

	public void setTeacher(Teacher teacher) {
		this.teacher = teacher;
	}

	public Student(int age, String name) {
		this.age = age;
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public Object clone() throws CloneNotSupportedException {
		// 为什么我们第一行要调用super.clone()方法呢:
		/**
		 * 【要想正确使用该方法:必须实现标识性接口Cloneable】 Cloneable接口中有如下详细说明: A class
		 * implements the Cloneable interface to indicate to the Object.clone()
		 * (实现Cloneable接口表明象征着Object的clone方法)
		 * method that it is legal for that method to make a field-for-field
		 * (通过属性到属性的拷贝该类的对象是合法的)
		 * copy of instances of that class.
		 * 
		 * Invoking Object's clone method on an instance that does not implement
		 * (如果执行Object的clone方法在一个对象上,并且这个对象的类没有实现Cloneable接口)
		 * the Cloneable interface results in the exception
		 * (那么将会导致如下一场)
		 * CloneNotSupportedException being thrown.
		 * 
		 * 1.首先,clone()方法是来自Object的,在Object类中,clone()是native修饰的
		 * 这就是说明,clone()的实现是由c或者c++来实现的,具体的实现代码我们是看不到的
		 * 
		 * 2.Object 的clone方法是protected的所以我们定义的时候一定要注意将访问修饰符修改成public
		 * 
		 * 3.那么调用super.clone()方法的时候都做了些什么呢? 做了这些工作:
		 * (1):Object的clone()方法识别你要赋值的是哪个对象,并为对象分配空间 (2):为对象的属性赋值
		 * 
		 */
		Student student = (Student)super.clone();
//		【重点:这种方式是为了实现深度复制,究其原因就是,只有我们自己逐层调用clone()方法才能实现深度复制】
		student.setTeacher((Teacher)student.getTeacher().clone());
		return student;
	}

}
class Teacher implements Cloneable
{
	private int age;
	private String name;
	public Teacher(int age, String name) {
		this.age = age;
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	@Override
	public Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
}

你可能感兴趣的:(object)