Java构造函数之调用父类构造函数
子類(lèi)可以通過(guò)super關(guān)鍵字來(lái)顯式地調(diào)用父類(lèi)的構(gòu)造函數(shù)。
當(dāng)父類(lèi)沒(méi)有提供無(wú)參數(shù)的構(gòu)造函數(shù)時(shí),子類(lèi)的構(gòu)造函數(shù)中必須顯式的調(diào)用父類(lèi)的構(gòu)造函數(shù);
如果父類(lèi)提供了無(wú)參數(shù)的構(gòu)造函數(shù),此時(shí)子類(lèi)的構(gòu)造函數(shù)就可以不顯式的調(diào)用父類(lèi)的構(gòu)造函數(shù),默認(rèn)調(diào)用父類(lèi)的無(wú)參構(gòu)造函數(shù)。
package com.bjut.StudyTest;class Person {public Person() {System.out.println("Base has no args.");}public Person(String temp) {System.out.println("Base:" + temp);} }class Student extends Person {public Student() {super("a");System.out.println("Student has no args.");}public Student(String temp) {System.out.println("Student:" + temp);} }public class TestConstruction {public static void main(String[] args) {Person p = new Student(); // 先調(diào)用父類(lèi)的構(gòu)造函數(shù),顯示調(diào)用指定的父類(lèi)構(gòu)造函數(shù)。Student s = new Student("b"); // 先調(diào)用父類(lèi)的構(gòu)造函數(shù),默認(rèn)調(diào)用父類(lèi)無(wú)參構(gòu)造函數(shù)。}} 輸出: Base:a Student has no args. Base has no args. Student:b當(dāng)有父類(lèi)時(shí),在實(shí)例化對(duì)象時(shí)會(huì)先執(zhí)行父類(lèi)的構(gòu)造函數(shù),然后執(zhí)行子類(lèi)的構(gòu)造函數(shù)。
(補(bǔ)充)java 程序初始化工作執(zhí)行的順序:
? ? ?父類(lèi)靜態(tài)變量 -> 父類(lèi)靜態(tài)代碼塊?-> 子類(lèi)靜態(tài)變量?-> 子類(lèi)靜態(tài)代碼塊
?-> 父類(lèi)非靜態(tài)變量 -> 父類(lèi)非靜態(tài)代碼塊 -> 父類(lèi)構(gòu)造函數(shù)
?-> 子類(lèi)非靜態(tài)代碼塊 -> 子類(lèi)非靜態(tài)變量 -> 子類(lèi)構(gòu)造函數(shù)
總結(jié)
以上是生活随笔為你收集整理的Java构造函数之调用父类构造函数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java.lang.NoSuchMeth
- 下一篇: C# 全屏截图实现方法