07数组与接口
1、運行TextInherists.java 示例,觀察輸出,注意總結(jié)父類與子類之間構(gòu)造方法的的調(diào)用關(guān)系,修改parent構(gòu)造方法的代碼,顯式調(diào)用grandparent另一個構(gòu)造函數(shù)。
源代碼:
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");//調(diào)用父類有參數(shù)的構(gòu)造函數(shù) 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"); } }?
運行結(jié)果截圖:
修改后的截圖:
通過super()調(diào)用父類構(gòu)造方法,必須在子類構(gòu)造方法的第一句。
?
2、為什么子類的構(gòu)造方法在運行之前,必須調(diào)用父類的構(gòu)造方法?能不能反過來?為什么不能反過來?
構(gòu)造函數(shù)的作用是初始化對象,類繼承了父類,就默認(rèn)含有父類的公共成員方法和公共成員變量,這些不再子類中重復(fù)聲明。而構(gòu)造方法則相當(dāng)于把父類給實例化出來,
如果子類實例化的時候不調(diào)用父類的構(gòu)造方法,相當(dāng)于子類壓根就沒有父親。不能反過來。
3、在子類中,如果調(diào)用父類被覆蓋的方法,可以使用super關(guān)鍵字。
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(); } }運行結(jié)果截圖:
?
轉(zhuǎn)載于:https://www.cnblogs.com/jingxiaopu/p/6049076.html
總結(jié)
- 上一篇: Angular之简单的登录注册
- 下一篇: 2017全国省市区县 json数据