62,621
社区成员
发帖
与我相关
我的任务
分享
class DeeplyClone {
public static void main(String[] args) {
Professor p = new Professor("feiyang", 23);
Student s1 = new Student("zhangshan", 18, p);
Student s2 = (Student) s1.clone();
s2.p.name = "Bill.Gates";//这里好象用的是Professor的clone方法.具体说法是怎么说的?
s2.p.age = 30;//请各位帮忙解答下;
System.out.println("name=" + s1.p.name + "," + "age=" + s1.p.age);
}
}
class Professor implements Cloneable {
String name;
int age;
Professor(String name, int age) {
this.name = name;
this.age = age;
}
public Object clone() {
Object o = null;
try {
o = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}
}
class Student implements Cloneable {
Professor p;
String name;
int age;
Student(String name, int age, Professor p) {
this.name = name;
this.age = age;
this.p = p;
}
public Object clone() {
//Object o=null;
Student o = null;
try {
o = (Student) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
o.p = (Professor) p.clone();
return o;
}
}