时间紧张,先记一笔,后续优化与完善。

    每日一道理
翻开早已发黄的页张,试着寻找过去所留下的点点滴滴的足迹。多年前的好友似乎现在看来已变得陌生,匆忙之间,让这维持了多年的友谊变淡,找不出什么亲切感,只是偶尔遇上,淡淡地微笑,如今也只能在这发黄的页张中找寻过去的那些让人难忘的,至少我可以握住这仅剩下一段的“丝线头”……
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();
}
}

文章结束给大家分享下程序员的一些笑话语录: 马云喜欢把自己包装成教主,张朝阳喜欢把自己包装成明星,李彦宏喜欢把自己包装成的很知性,丁磊喜欢把自己包装的有创意,李开复总摆出一副叫兽的样子。看来的。其实我想说,缺啥补啥,人之常情。

---------------------------------
原创文章 By
方法和object
---------------------------------

04-09 08:49