07数组与接口
1、運行TextInherists.java 示例,觀察輸出,注意總結父類與子類之間構造方法的的調用關系,修改parent構造方法的代碼,顯式調用grandparent另一個構造函數。
源代碼:
class GrandParent{ public GrandParent(){ System.out.println("GrandParent Created"); }public GrandParent(String string){ System.out.println("GrandParent Created"+string); } } class Parent extends GrandParent{ public Parent(){ super("123");//調用父類有參數的構造函數 System.out.println("Parent Created"); } } class Child extends Parent{ public static void main(String[] args){ Child c=new Child(); }public Child(){ System.out.println("Child Created"); } }?
運行結果截圖:
修改后的截圖:
通過super()調用父類構造方法,必須在子類構造方法的第一句。
?
2、為什么子類的構造方法在運行之前,必須調用父類的構造方法?能不能反過來?為什么不能反過來?
構造函數的作用是初始化對象,類繼承了父類,就默認含有父類的公共成員方法和公共成員變量,這些不再子類中重復聲明。而構造方法則相當于把父類給實例化出來,
如果子類實例化的時候不調用父類的構造方法,相當于子類壓根就沒有父親。不能反過來。
3、在子類中,如果調用父類被覆蓋的方法,可以使用super關鍵字。
class Friut{ public void show(){ System.out.println("Fruit!"); } } class Apple extends Friut{public void show(){ System.out.println("Apple!"); super.show(); } }public class fangFaSuper{ public static void main(String[] args){ Apple a=new Apple(); a.show(); } }運行結果截圖:
?
轉載于:https://www.cnblogs.com/jingxiaopu/p/6049076.html
總結
- 上一篇: Angular之简单的登录注册
- 下一篇: 2017全国省市区县 json数据