构造器内部的多态方法的行为

每天发出自己学习的内容,坚持坚持。。。

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 构造器内部的多态方法的行为
{
public static void main(String[] args)
{
new RoundGlyph(5);
}

}
/**

输出:

Glyph() before draw()
RoundGlyph.draw(),radius=0
Glyph() after draw()
RoundGlyph.RoundGlyph(),radius=5


基类Glyph的构造器中调用了被子类RoundGlyph覆盖的draw()方法,并且输出了radius=0,这显然是一个错误,因为这个"0"是在其他任何事物发生之前,
系统分配给对象的储存空间的初始值--二进制的零,而非我们想要设定的初始值"1",这是因为,我们在创建子类(RoundGiyph)对象时会先调用基类(Glyph)
的构造器构造基类对象,而在基类的构造器中却调用了被子类覆盖的动态绑定的方法(draw()),而这个方法所操作的可能是子类中的还未进行初始化的成员(radius)
,这便会招致灾难,尽管编译器并没有报错。
在构造器中,唯一能够安全调用的是基类中的final方法(包括private方法),因为这些方法不能被子类覆盖,也就不会出现上述的问题
*/

原文地址:https://www.cnblogs.com/fanzhengzheng/p/7476255.html