子類繼承了父類,子類就擁有父類的成員變量和方法龟再。子類實例化時首先為父類定義的成員變量分配和初始化书闸。這就需要調用父類的構造方法。默認是調用父類的默認構造方法利凑,如果父類沒有無參的構造方法浆劲,就需要在子類的構造方法中顯示地調用父類的構造方法嫌术,并且放在構造方法的第一語句。否則發(fā)生編譯錯誤牌借。
下例中度气,子類的構造方法Soun(int a,int b,int c)在第一語句就調用父類Father(int a,int b)構造方法,調用父類構造方法使用關鍵字super膨报。 ?如果不這樣做將隱式調用默認父類默認構造方法磷籍,而本例的Father類并沒有提供,將會報編譯錯誤丙躏。
classFather {
inta;
intb;
publicFather(inta,intb){
this.a=a;
this.b=b;
}
publicvoidprintLine(){
System.out.println("------------");
}
publicvoidprintValue(){
System.out.println("a="+a+"\tb="+b);
}
}
classSonextendsFather{
intc;
publicSon(inta,intb,intc){
super(a,b);
this.c=c;
}
publicvoidprintValue(){
System.out.println("a="+a+"\tb="+b+"\tc="+c);
}
publicvoidprintStar(){
System.out.println("************");
}
}
publicclassDemo1 {
publicstaticvoidmain(String[]args) {
Sonson=newSon(1,2,3);
son.printLine();
son.printStar();
son.printValue();
}
}
運行程序择示,結果如下圖所示: