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);
}
}
class RectangularGlyph extends Glyph {
private int length = 2;
private int width = 4;
RectangularGlyph(int l, int w) {
length = l;
width = w;
print("RectangularGlyph.RectangularGlyph(), length = "
+ length + ", width = " + width);
}
void draw() {
print("RectangularGlyph.draw(), length = " + length
+ ", width = " + width);
}
}
public class PolyConstructors15 {
public static void main(String[] args) {
new RoundGlyph(5);
new RectangularGlyph(3, 6);
}
}
output:
Glyph() before draw()
RoundGlyph.draw(), radius = 0
Glyph() after draw()
RoundGlyph.RoundGlyph(), radius = 5
Glyph() before draw()
RectangularGlyph.draw(), length = 0, width = 0
Glyph() after draw()
RectangularGlyph.RectangularGlyph(), length = 3, width = 6
注意初始化顺序:
1、在任何事情发生之前,将分配给对象的存储空间初始化成二进制的0。
2、调用父类构造器,调用被子类覆盖的方法,由于子类构造器尚未执行,此时子类中的radius仍然是0.
3、按照声明的顺序调用成员的初始化方法。
4、调用子类的构造器。