初始化的实际过程是这样的:
(1) 在采取其他任何操作之前,为对象分配的存储空间初始化成二进制零。
(2) 就象前面叙述的那样,调用基础类构建器。此时,被覆盖的draw()方法会得到调用(的确是在
RoundGlyph 构建器调用之前),此时会发现radius 的值为0,这是由于步骤(1)造成的。
(3) 按照原先声明的顺序调用成员初始化代码。
(4) 调用衍生类构建器的主体。
- package polymorphism;
- //: polymorphism/PolyConstructors.java
- // Constructors and polymorphism
- // don't produce what you might expect.
- import static net.mindview.util.Print.*;
- class Glyph {
- void draw() { print("Glyph.draw()"); }
- Glyph() {
- print("Glyph() before draw()");
- draw();
- print("Glyph() after draw()");
- }
- }
- class RoundGlyph extends Glyph {
- private int radius = 1;
- RoundGlyph(int r) {
- radius = r;
- print("RoundGlyph.RoundGlyph(), radius = " + radius);
- }
- void draw() {
- print("RoundGlyph.draw(), radius = " + radius);
- }
- }
- public class PolyConstructors {
- public static void main(String[] args) {
- new RoundGlyph(5);
- }
- } /* Output:
- Glyph() before draw()
- RoundGlyph.draw(), radius = 0
- Glyph() after draw()
- RoundGlyph.RoundGlyph(), radius = 5
- */
FROM:《Thinking in Java》fourth edition 7.7.3构建器内部的多形性方法的行为
阅读(1618) | 评论(0) | 转发(0) |