若是你的方法覆蓋了它的一個超類的方法,你能夠經過使用關鍵字super
來調用被重寫的方法,你也能夠使用super
來引用隱藏字段(儘管不鼓勵隱藏字段),慮這個類,Superclass
:segmentfault
public class Superclass { public void printMethod() { System.out.println("Printed in Superclass."); } }
這是一個名爲Subclass
的子類,它重寫了printMethod()
:ide
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(); } }
在Subclass
中,簡單名稱printMethod()
引用在Subclass
中聲明的名稱,它覆蓋了Superclass
中的名稱,所以,要引用從Superclass
繼承的printMethod()
,Subclass
必須使用限定名,使用super
,編譯和執行Subclass
將打印如下內容:函數
Printed in Superclass. Printed in Subclass
如下示例說明如何使用super
關鍵字來調用超類的構造函數,回想一下Bicycle
的例子,MountainBike
是Bicycle
的子類,這是MountainBike
(子類)構造函數,它調用超類構造函數,而後添加本身的初始化代碼:code
public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) { super(startCadence, startSpeed, startGear); seatHeight = startHeight; }
調用超類構造函數必須是子類構造函數中的第一行。繼承
調用超類構造函數的語法是:get
super();
或編譯器
super(parameter list);
使用super()
,能夠調用超類無參數構造函數,使用super(parameter list)
,將調用具備匹配參數列表的超類構造函數。編譯
注意:若是構造函數沒有顯式調用超類構造函數,Java編譯器會自動插入對超類的無參數構造函數的調用,若是超類沒有無參數構造函數,則會出現編譯時錯誤,Object
確實有這樣的構造函數,所以若是Object
是惟一的超類,則沒有問題。
若是子類構造函數顯式或隱式調用其超類的構造函數,你可能會認爲將調用一整個構造函數鏈,一直返回Object
的構造函數,事實上,狀況就是這樣,它被稱爲構造函數鏈,當須要很長的類層次時,你須要意識到這一點。class