Java子類與父類中靜態程式碼塊、非靜態程式碼塊、建構函式的執行順序一覽表
阿新 • • 發佈:2018-11-11
子類Child繼承父類Parent
Child child=new Child();
執行順序如下:
①父類靜態程式碼塊>>②子類靜態程式碼塊>>③父類非靜態程式碼塊>>④父類建構函式>>⑤子類非靜態程式碼塊>>⑥子類建構函式
大致總結:
父類早於子類,靜態早於非靜態,非靜態早於建構函式。
1、驗證程式碼
package com.jdk; /** * Created by Liuxd on 2018-11-02. */ public class TestClass { public static void main(String[] args) { new Child("param"); } } class Parent { static { System.out.println("執行父類靜態程式碼塊"); } { System.out.println("執行父類構造程式碼塊"); } Parent() { System.out.println("執行父類無引數構造方法"); } Parent(String str) { System.out.println("執行父類帶引數構造方法,引數:" + str); } } class Child extends Parent { static { System.out.println("執行子類靜態程式碼塊"); } { System.out.println("執行子類構造程式碼塊"); } Child() { System.out.println("執行子類無引數構造方法"); } Child(String str) { super(str); System.out.println("執行子類帶引數構造方法,引數" + str); } }
2、執行結果,一目瞭然
執行父類靜態程式碼塊
執行子類靜態程式碼塊
執行父類構造程式碼塊
執行父類帶引數構造方法,引數:param
執行子類構造程式碼塊
執行子類帶引數構造方法,引數param