gpt4 book ai didi

java - 为什么父构造函数中的方法实际上调用子方法

转载 作者:行者123 更新时间:2023-11-30 06:12:55 24 4
gpt4 key购买 nike

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

@Override
void draw() {
System.out.println("roundGlyph.draw:" + radius);
}
}

public class PolyConstructors {
public static void main(String[] args) {
new RoundGlyph(3);
}
}

输出是:

glyph() before draw
**roundGlyph.draw:0**
glyph() after draw
roundGlyph.RoundGlyph:3

我对第二个结果感到困惑,为什么父类构造函数中的代码draw(),实际上调用的是子draw方法而不是父draw方法?

最佳答案

这样 draw() 调用就是调用 this.draw(),其中 this 是您的实例化对象。

在这种情况下,this 指的是一个类型为 RoundGlyph 的对象,它已经覆盖了 Draw() 方法。在 RoundGlyph 对象的上下文中,没有打印 "glyph.draw()"Draw 方法,那没了。

关于java - 为什么父构造函数中的方法实际上调用子方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32390688/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com