【发布时间】:2019-09-30 14:55:59
【问题描述】:
我对这个代码示例感到困惑:
我很困惑为什么要先调用 draw 的子方法。我很困惑,因为当在 main 中实例化 RoundGlyph 时,超级构造函数不是在子对象之前实例化父对象吗?
class Glyph {
void draw() {
System.out.println("test"); // method will be called once you create a Glyph object, because when we create a round glyph before creating a glyph the super constructor will be called
}
void print2() {
System.out.println("printed from print 2");
}
int y1;
Glyph() {
y1 = 5;
System.out.println("y1 = " + y1);
System.out.println("Glyph() before draw()");
draw();
System.out.println("Glyph() after draw()");
print2();
}
}
class RoundGlyph extends Glyph {
int radius = 1;
RoundGlyph(int r) {
System.out.println("radius in RoundGlyph=" + radius);
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);
//new Glyph();
}
}
【问题讨论】:
-
因为它是在 RoundGlyph 的一个实例上调用的
-
构造函数是隐式调用的。 draw() 方法在孩子中被覆盖,因此它将被调用而不是父方法。
-
如果要执行父级的代码,可以使用super();
-
这就是为什么你应该从不在构造函数中调用一个可覆盖的方法。
标签: java inheritance