07课堂问题整理
作業(yè)歸檔7 繼承與接口
完成課件中的動手動腦的或需要驗(yàn)證的相關(guān)內(nèi)容。
1、運(yùn)行 TestInherits.java 示例,觀察輸出,注意總結(jié)父類與子類之間構(gòu)造方法的調(diào)用關(guān)系修改Parent構(gòu)造方法的代碼,顯式調(diào)用GrandParent的另一個(gè)構(gòu)造函數(shù),注意這句調(diào)用代碼是否是第一句,影響重大!
代碼:
class Grandparent {
????public Grandparent() {
????????System.out.println("GrandParent Created.");
????}
????public Grandparent(String string) {
????????System.out.println("GrandParent Created.String:" + string);
????}
}
class Parent extends Grandparent {
????public Parent() {
????????//super("Hello.Grandparent.");
????????System.out.println("Parent Created");
????????//super("Hello.Grandparent.");
????}
}
class Child extends Parent {
????public Child() {
????????System.out.println("Child Created");
????}
}
public class TestInherits {
????public static void main(String?args[]) {
????????Child c?= new Child();
????}
}
運(yùn)行結(jié)果:
GrandParent Created.
Parent Created
Child Created
當(dāng)把第一個(gè)//super("Hello.Grandparent.");的//去掉后,運(yùn)行結(jié)果是
GrandParent Created.String:Hello.Grandparent.
Parent Created
Child Created
說明super可以調(diào)用父類的構(gòu)造方法。
若是把第二個(gè)//super("Hello.Grandparent.");的//去掉后,將會出現(xiàn)編譯錯(cuò)誤Constructor call must be the first statement in a constructor。說明要用super調(diào)用父類構(gòu)造方法,必須是在子類構(gòu)造方法中的第一句。
為什么子類的構(gòu)造方法在運(yùn)行之前,必須調(diào)用父類的構(gòu)造方法?
子類是通過父類繼承過來的,所以子類有父類的屬性和方法,如果不調(diào)用父類的構(gòu)造方法,無法初始化父類中定義的屬性,無法給父類的屬性分配內(nèi)存空間。
2、請自行編寫代碼測試以下特性(動手動腦):在子類中,若要調(diào)用父類中被覆蓋的方法,可以使用super關(guān)鍵字。
public class YanZheng {
????public static void main(String []args){
???? Pear pear=new Pear();
???? pear.output();
????}
}
class Apple{
public void output(){
System.out.println("父類:蘋果。");
}
}
class Pear extends Apple{
public void output(){
super.output();
System.out.println("子類:梨。");
}
}
運(yùn)行結(jié)果:
父類:蘋果。
子類:梨。
轉(zhuǎn)載于:https://www.cnblogs.com/hjy415/p/6055459.html
總結(jié)
- 上一篇: Python类的实例属性详解
- 下一篇: 2016级算法第二次上机-F.Modri