clone的问题

skyair2004 2009-07-13 09:50:53

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;
}
}
...全文
77 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
skyair2004 2009-07-14
  • 打赏
  • 举报
回复
谁说下应该怎么描叙那里哦
skyair2004 2009-07-14
  • 打赏
  • 举报
回复
能不能来个详细的解释哦
zhongying125 2009-07-14
  • 打赏
  • 举报
回复

s2.p.name = "Bill.Gates";//这里好象用的是Professor的clone方法.具体说法是怎么说的?

这个name 是Professor的属性,而非Student的属性,当被包含类被克隆调用时,自动调用其本身的克隆方法。
skyair2004 2009-07-13
  • 打赏
  • 举报
回复
对啊,我问的就是这个问题.我知道是调用了那个方法
能讲下这个多态吗
ouyangyh 2009-07-13
  • 打赏
  • 举报
回复
LZ你的Student那个类的clone方法后面调用了Professor的克隆方法

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧