如果在超类的构建器中调用了子类覆盖过的方法,则编译器默认会调用在超类构建的过程中调用已经被子类覆盖过的方法,而不是超类中的原始方法。这种错误很难从逻辑上进行排查,所以一定要格外小心!以下是例子:
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);
}
}
/*output
Glyph () before draw()
RoundGlyph.draw().radius = 0
Glyph () after draw()
RoundGlyph.RoundGlyph().radius = 5
*/
我们本来应该得到的draw()方法应该是超类未被覆盖的draw()方法,然而编译器调用的却是子类中的draw()方法。而此时子类构建器还未初始化,但是在实例已经给对象的存储空间初始化成二进制的0,所以看到radius为0而不是1 。