回 帖 发 新 帖 刷新版面

主题:[讨论]Thinking in Java 3中的一个程序

class Glyph {
  void draw(){System.out.println("Glyph.draw()");};
  Glyph() {
    System.out.println("Glyph() before draw()");
    draw();
    System.out.println("Glyph() after draw()");
  }
}

class RoundGlyph extends Glyph {
  private int radius = 1;
  RoundGlyph(int r) {
    radius = r;
    System.out.println(
      "RoundGlyph.RoundGlyph(), radius = " + radius);
  }
  void draw() {
    System.out.println(
      "RoundGlyph.draw(), radius = " + radius);
  }
}

public class PolyConstructors {
    public static void main(String[] args) {
    new RoundGlyph(5);    
  }
} ///:~
程序运行结果是:

Glyph() before draw()
RoundGlyph.draw(), radius = 0
Glyph() after draw()
RoundGlyph.RoundGlyph(), radius = 5
第二行调用了派生类的draw()函数,为什么?

回复列表 (共1个回复)

沙发

因为在派生类中覆盖了draw()方法

我来回复

您尚未登录,请登录后再回复。点此登录或注册