Java替代说明 [英] Java override explanation
问题描述
这是我的代码
class Glyph {
void draw() { System.out.println("Glyph.draw()"); }
Glyph(int i) {
System.out.println("Glyph() before draw()");
draw();
System.out.println("Glyph() after draw()");
}
}
class RoundGlyph extends Glyph {
private int radius = 1;
RoundGlyph(int r) {
super(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);
}
}
输出:
Glyph() before draw()
RoundGlyph.draw(), radius = 0
Glyph() after draw()
RoundGlyph.RoundGlyph(), radius = 5
为什么超类Glyph
的构造函数调用子类RoundGlyph
的draw方法?如何从超类的构造函数中调用超类的draw方法?我试过了,但是没用....
Why is the constructor of the superclass Glyph
calling the draw method of the subclass RoundGlyph
? How can I call the draw method of the superclass from the constructors of the superclass? I tried this but it didn't work....
推荐答案
为什么子类的超级调用draw方法的构造方法
Why the Constructors of super calling draw method of sub classs
这是方法覆盖起作用的方式.如果子类实现了与其父(或祖父母等)具有相同签名的方法,则当其祖先之一调用该方法而未指定super.
时,将调用该子类的版本.
This is the way that method overriding works. If a subclass has implemented a method with the same signature as its parent (or grandparent, etc), when one of its ancestors calls that method without specifying super.
, the sublcass's version will be called.
我将如何从super的构造函数中调用super的方法
how i will be able to call method of super from Constructors of super
与子类的版本相反,没有一种方法可以指定调用方法的 my 版本.
There isn't a way to specify calling my version of a method, as opposed to a subclass's version.
请注意,除了设置类所必需的之外,您不应在构造函数中进行任何工作.
Please note that you shouldn't do any work in a constructor other than what is necessary to set up the class.
这篇关于Java替代说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!