在子父类的构造函数中存在以下关系:
1:在调用子类构造函数时,父类构造函数也会运行
因为在子类构造函数中,隐式地认为第一行为super(),即调用父类的无参数构造方法。
如果父类没有无参数构造方法,那么需要在子类中给出父类的含参构造方法。
如果父类中没有构造函数,那么子类中就无需给出任何父类的构造函数。
2:如果需要调用父类的含参构造函数,必须在子类构造方法的第一行调用
3:this与super都只能出现在第一行,所以这两者只能选择一个使用。
public class Test {
public static void main(String args[]){
new RoundGlyph(5);
}
}
class Glyph{
void draw(){
System.out.println("Glyph.draw()");
}
Glyph() {
System.out.println("Glyph before.draw()");
draw();
System.out.println("Glyph after.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();隐式调用
radius = r;
System.out.println("RoundGlyph.RoundGlyph(), radius = " + radius);
}
void draw(){
System.out.println("RoundGlyph.draw(), radius = " + radius);
}
}