Chinaunix首页 | 论坛 | 博客
  • 博客访问: 436557
  • 博文数量: 67
  • 博客积分: 2468
  • 博客等级: 上尉
  • 技术积分: 1050
  • 用 户 组: 普通用户
  • 注册时间: 2011-01-05 01:21
文章分类

全部博文(67)

文章存档

2013年(1)

2012年(65)

2011年(1)

分类: Java

2012-07-06 13:01:47

初始化的实际过程是这样的:
(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构建器内部的多形性方法的行为
阅读(1572) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~