【发布时间】:2010-01-27 09:40:51
【问题描述】:
我正在向我的朋友解释 OOP。我无法回答这个问题。
我只是逃避说,因为 OOP 描绘的是真实世界。在现实世界中,父母可以容纳孩子,但孩子不能容纳父母。在 OOP 中也是如此。
class Parent
{
int prop1;
int prop2;
}
class Child : Parent // class Child extends Parent (in case of Java Lang.)
{
int prop3;
int prop4;
public static void Main()
{
Child aChild = new Child();
Parent aParent = new Parent();
aParent = aChild;// is perfectly valid.
aChild = aParent;// is not valid. Why??
}
}
为什么这个陈述无效?
aChild = aParent;// is not valid. Why??
因为aChild 的成员是aParent 的成员的超集。那为什么aChild不能容纳父母呢。
【问题讨论】:
-
父母是通用的,子是专业的。铅笔是一块木头,但木头不是铅笔。铅笔是相当具体的附加属性。