java 多态构造方法_Java,在构造器里调用多态方法

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);

}

void superDraw(){

super.draw();

}

}

public class PolyConstructors {

public static void main(String[] args) {

RoundGlyph rg = new RoundGlyph(5);

rg.superDraw();

}

}

这样一段代码,执行结果是这样的:

Glyph() before draw()

RoundGlyph.draw(), radius = 0

Glyph() after draw()

RoundGlyph.RoundGlyph(), radius = 5

Glyph.draw()

Thinking In Java中有一句话

Glyph.draw()方法设计将要被覆盖,这种覆盖是在RoundGlyph中发生的。(这里都OK)但是Glyph构造器会调用这个方法,结果导致了对RoundGlyph.draw()的调用。

这句话我就不太明白了,①为什么Glyph的构造器会去调用子类的draw方法而不去调用自己的draw方法呢?重写明明是在子类中发生的呀,父类中的draw方法并没有被重写吧(看我后来又调了super.draw,结果也是父类中的draw方法)。

常见的多态代码是向上转型,把一个子类的实例赋值给父类的引用,这时候产生多态,这个我知道。但是②这个多态是怎么产生的呢?

主要就是①②这两个问题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值