如果你的方法覆寫一個(gè)父類成員的方法, 你可以通過(guò) super 關(guān)鍵字調(diào)用父類的方法. 考慮下面的父類:
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
下面是一個(gè)子類 (subclass), 叫做 Subclass, 覆寫了 printMethod():
public class Subclass extends Superclass {
// overrides printMethod in Superclass
public void printMethod() {
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
輸出
Printed in Superclass.
Printed in Subclass
使用 super 關(guān)鍵字調(diào)用父類的構(gòu)造函數(shù). 下面的 MountainBike 類是 Bicycle 類的子類. 它調(diào)用了父類的構(gòu)造方法并加入了自己的初始化代碼:
public MountainBike(int startHeight,
int startCadence,
int startSpeed,
int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}
調(diào)用父類的構(gòu)造體必須放在第一行.
使用
super();
或者:
super(parameter list);
通過(guò) super(), 父類的無(wú)參構(gòu)造體會(huì)被調(diào)用. 通過(guò) super(parameter list), 父類對(duì)應(yīng)參數(shù)的構(gòu)造體會(huì)被調(diào)用.
注意: 構(gòu)造體如果沒(méi)有顯式的調(diào)用父類的構(gòu)造體, Java 編譯器自動(dòng)調(diào)用父類的無(wú)參構(gòu)造. 如果父類沒(méi)有無(wú)參構(gòu)造, 就會(huì)報(bào)錯(cuò) ( compile-time error).