//impori static net.mindview.util.System.out.println.*;//静态导入
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.draw(),radius="+radius);
}
void draw(){
System.out.println("RoundGlyph.draw(),radius="+radius);
}
}
public class PolyConstructors{
public static void main(String[] args){
new RoundGlyph(5);
System.out.println("\n");
new Glyph();
}
}/*output:
Glyph() before draw()
RoundGlyph.draw(),radius=0
Glyph() after draw()
RoundGlyph.draw(),radius=5
Glyph() before draw()
Glyph.draw()
Glyph() after draw()
*///:~
Glyph.draw()方法设计为被覆盖,而这个覆盖是在子类 RoundGlyph中发生的.当创建一个new RoundGlyph()对象的时候,会先初始化基类Glyph,可以这么理解,子类是构造在父类基础之上的,必须先初始化父类才能调用创建子类.在子类构造方法中内涵super(),只是隐藏起来罢了,并且 super()必须用在子类构造函数的第一行.调用子类draw()方法后radius结果是0而非1,因为属性radius在父类中没有定义而初始化值就是0.创建子类的时候对父类的初始化可以理解为
RoundGlyph(int r){
super();
radius=r;
System.out.println("RoundGlyph.draw(),radius="+radius);
}
进而可以看成:
RoundGlyph(int r){
System.out.println("Glyph() before draw()");
draw();
System.out.println("Glyph() after draw()");
radius=r;
System.out.println("RoundGlyph.draw(),radius="+radius);
}