续《JAVA编程思想》学习备忘(第277页Polymorphism-2)
Behavior of polymorphic methods inside constructors
示例:
class Glyph {
}
class RoundGlyph extends Glyph{
}
public class PolyConstructors {
}
输出:
Glyph() before draw()
RoundGlyph.draw(),radius = 0
Glyph() after draw()
RoundGlyph.RoundGlyph(),radius = 5
为什么在父类构造函数还没有完成时,子类的重写方法确已经执行了呢?
来看上例初始化的实际进程:
1、在任何事物发生之前,内存为对象开辟空间被初始化为二进制大小0;
2、父类构造函数首先被调用,在此点,调用了重写的draw()方法,根据进程1得知:radius被付值为0;
3、按声明顺序调用成员初始化者;
4、子类的构造函数体被调用。
Covariant return types
Java SE5 adds covariant return types,which means that an overridden method in a derived class can return a type derived from the type returned by the base-class method:
class Grain {
}
class Wheat extends Grain{
}
class Mill{
}
class WheatMill extends Mill{
}
public class CovariantReturn {
}
输出:
Grain
Wheat
Designing with inheritance
...A better approach is to choose composition first,especially when it's not obvious which one you should use.Composition does not force a design into an inheritance hierarchy.But composition is also more flexble since it's possible to dynamically choose a type(and thus behavior)when using composition,whereas inheritance requires that an exact type be known at compile time.The following example illustrates this:
class Actor {
}
class HappyActor extends Actor{
}
class SadActor extends Actor{
}
class Stage{
}
public class Transmogrify {
}
输出:
HappyActor
SadActor
A general guideline is "Use inheritance to express differences in behavior,and fields to express variations in state."
Substitution vs. extension
...the base class can receive any message you can send to the derived class because the two have exactly the same interface.
Downcasting and runtime type information
(类型)向下强转与运行时类型信息
示例:
class Useful {
}
class MoreUseful extends Useful{
}
public class RTTI {
}
Summary
Polymorphism means"different forms."In OOP,you have the same interface from the base class,and different forms using that interface:the different versions of the dynamically bound methods.