Java高级特性之clone方法(一)

来源:互联网 发布:数据封装和拆封过程 编辑:程序博客网 时间:2024/05/16 01:39
package three.day.newcharacter;




public class ObjectCloneDemo01 {


/**
* @param args
*/
public static void main(String[] args) {
Professor p = new Professor("jiaoshu",50);
Student stu1 = new Student("zhangsan",19,p);
Student stu2 =(Student) stu1.clone();
stu2.name="wangba";
stu2.age = 21;
stu2.p.name = "gaibian";
stu2.p.age = 30;
System.out.println("stu1.name="+stu1.name+",stu1.age="+stu1.age);
System.out.println("stu1.p.name="+stu1.p.name+",stu1.p.age"+stu1.p.age);
}


}
class Professor implements Cloneable
{
String name;
int age;
public Professor(String name,int age)
{
this.name = name;
this.age = age;
}
public Object clone() throws CloneNotSupportedException
{
Object p = null;
p = super.clone();
return p;

}
}
class Student implements Cloneable 
{
String name;
int age;
Professor p;
public Student(String name,int age,Professor p)
{
this.name=name;
this.age=age;
this.p = p;
}
public Object clone()
{
Student o = null;
try
{
o = (Student) super.clone();
}
catch(CloneNotSupportedException ce)
{
System.out.println(ce.toString());
}
try {
o.p = (Professor) p.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}
}