java的类初始化过程

1650阅读 0评论2012-07-06 时间看来
分类:Java

初始化的实际过程是这样的:
(1) 在采取其他任何操作之前,为对象分配的存储空间初始化成二进制零。
(2) 就象前面叙述的那样,调用基础类构建器。此时,被覆盖的draw()方法会得到调用(的确是在
RoundGlyph 构建器调用之前),此时会发现radius 的值为0,这是由于步骤(1)造成的。
(3) 按照原先声明的顺序调用成员初始化代码。
(4) 调用衍生类构建器的主体。

点击(此处)折叠或打开

  1. package polymorphism;

  2. //: polymorphism/PolyConstructors.java
  3. // Constructors and polymorphism
  4. // don't produce what you might expect.
  5. import static net.mindview.util.Print.*;

  6. class Glyph {
  7.   void draw() { print("Glyph.draw()"); }
  8.   Glyph() {
  9.     print("Glyph() before draw()");
  10.     draw();
  11.     print("Glyph() after draw()");
  12.   }
  13. }    

  14. class RoundGlyph extends Glyph {
  15.   private int radius = 1;
  16.   RoundGlyph(int r) {
  17.     radius = r;
  18.     print("RoundGlyph.RoundGlyph(), radius = " + radius);
  19.   }
  20.   void draw() {
  21.     print("RoundGlyph.draw(), radius = " + radius);
  22.   }
  23. }    

  24. public class PolyConstructors {
  25.   public static void main(String[] args) {
  26.     new RoundGlyph(5);
  27.   }
  28. } /* Output:
  29. Glyph() before draw()
  30. RoundGlyph.draw(), radius = 0
  31. Glyph() after draw()
  32. RoundGlyph.RoundGlyph(), radius = 5
  33. */

FROM:《Thinking in Java》fourth edition   7.7.3构建器内部的多形性方法的行为
上一篇:Java中super的几种用法并与this的区别
下一篇:初识ucos-II