標籤:繼承 運行 無法 created 初始化 int 而且 運算 string
(一)繼承條件下構造方法的調用
以下面的原始碼為例:
package ktdemo;class Grandparent { public Grandparent() { System.out.println("GrandParent Created."); } public Grandparent(String string,String str) { System.out.println("GrandParent Created.String:" + string + " "+ str); }}class Parent extends Grandparent { public Parent() { super("已經調用","該方法"); 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(); }}
修改Parent構造方法的代碼,在前面加一句調用super方法的語句,可以顯示調用GrandParent的另一個有參的構造方法。
沒加上super語句前運行:
加上super語句前運行:
從看說明通過可以super調用父類的有參和無參的構造方法
#而且必須是子類構造方法的第一個語句,因為構造方法的調用是先調用父類的構造方法,再調用子類的構造方法。
(二)為什麼子類的構造方法在運行之前,必須調用父類的構造方法?能不能反過來,為什麼不能反過來?
(1) 建構函式是一種特殊的函數,主要用來建立對象時初始化對象,即為對象成員變數賦初值,它與new 運算子一起使用在建立對象的語句中;建構函式的主要功能用於在類的·建立時定義初始化狀態
(2) 構造一個對象時,必須先調用其的建構函式,來初始化其成員變數和成員方法
(3) 子類擁有父類的成員變數和成員方法,子類繼承了父類的各種屬性,而構造方法則相當於把類給執行個體化出來,如果子類不調用父類的建構函式,則從父類繼承而來的各種屬性無法得到正確的初始化,不能反過來調用是因為父類根本不知道子類中有什麼變數和方法,而且這樣子類也得不到初始化的父類屬性,程式會出錯。
(三)方法覆蓋要求子類與父類的方法一模一樣,否則是方法重載,在子類中,若要調用父類中被覆蓋的方法,可以使用super關鍵字,範例程式碼:
package demo;class parent{ public void show() { System.out.println("這是父類中的show方法"); }}class child extends parent{ public void show() { super.show(); System.out.println("這是子類中的show方法"); }}public class test { public static void main(String [] args) { child c = new child(); c.show(); }
運行:
結果分析:super方法在子類覆蓋方法類使用,只有這樣才能調用父類中被覆蓋的方法,並且super語句放在子類覆蓋方法第幾句都行
java學習中一些疑惑解答(2)