class Glyph{
void draw(){
System.out.println("Glyph.draw()");
}
Glyph(){
System.out.println("Glyph() before draw()");
draw();
System.out.println("Glyh() 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);//先初始化基类的构造函数,然后覆盖draw()方法,再然后就是初始化导出类。
}
输出:
Glyph() before draw()
RoundGlyph.draw(),radius =0
Glyh() after draw()
RoundGlyph.RoundGlyph(),radius =5
问题: 为何会打印第二行呢?初始化基类构造器时调用的不是内部的draw()方法吗?
------解决方案--------------------
class Glyph{
void draw(){
System.out.println("Glyph.draw()");
}
Glyph(){
System.out.println("Glyph() before draw()"); // 1 调用父类无参构造方法
draw(); // 子类重写父类方法,固调用子类的draw
System.out.println("Glyh() after draw()"); // 3
}
}
class RoundGlyph extends Glyph{
private int radius = 1;
RoundGlyph(int r){
radius = r;
System.out.println("RoundGlyph.RoundGlyph(),radius ="+radius); // 4
}
void draw(){
System.out.println("RoundGlyph.draw(),radius ="+radius); // 2
}
}