下面是一段摘自thinking in java中的小程序:
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 TestPolymophic {
public static void main(String[] args) {
new RoundGlyph(5);
}
}
程序的输出结果是:
Glyph() before draw()
RoundGlyph.draw(), radius = 0
Glyph() after draw()
RoundGlyph.RoundGlyph(), radius = 5
不理解的地方:为什么会输出RoundGlyph.draw(), radius = 0???并且为什么radius=0???
------解决方案--------------------
这个问题貌似在以前的时候讨论过:
好像是:http://bbs.csdn.net/topics/390727330
------解决方案--------------------
new RoundGlyph(5);的时候,首先去调用父类的构造函数,
因而有输出:
Glyph() before draw()
RoundGlyph.draw(), radius = 0
Glyph() after draw()
中间一句是因为在调用父类的draw()时,因子类有重写,所以其实是调用了子类的draw();
即会执行System.out.println("RoundGlyph.draw(), radius = " + radius);一句
但此时子类对象还未构造好,因而radius为零,故有 RoundGlyph.draw(), radius = 0的输出。
此后 ,再去调用子类的构造函数,执行
RoundGlyph(int r) {
radius = r;
System.out.println("RoundGlyph.RoundGlyph(), radius = " + radius);
}
所以再输出RoundGlyph.RoundGlyph(), radius =5
------解决方案--------------------
用调试器一调,就清清楚楚。
加一下
public class Glyph {
public int num = 1;
void draw() {
System.out.println("Glyph.draw()");
}
Glyph() {
System.out.println("Glyph() before draw()");
//draw();
System.out.println("Glyph() after draw()");
}
public String address = "bbg";
}