前陣子看到阿里巴巴的一提面試題是關於java類的加載順序

package com.mikey.demo.Test; class FatherVariable{ static { System.out.println("FatherVariable Static Constructor Code"); } { System.out.println("FatherVariable Constructor Code"); } public FatherVariable() { System.out.println("FatherVariable Constructor Method"); } } class ChildVariable{ static { System.out.println("ChildVariable Static Constructor Code"); } { System.out.println("ChildVariable Constructor Code"); } public ChildVariable() { System.out.println("ChildVariable Constructor Method"); } } class Father{ static FatherVariable fatherVariable = new FatherVariable(); static { System.out.println("Father Static Constructor Code"); } { System.out.println("Father Constructor Code"); } public Father() { System.out.println("Father Constructor Method"); } } class Child extends Father { static ChildVariable childVariable = new ChildVariable(); static { System.out.println("Child Static Constructor Code"); } { System.out.println("Child Constructor Code"); } public Child() { System.out.println("Child Constructor Method"); } } public class Clazz { public static void main(String[] args) { new Child(); //父類靜態變量 //FatherVariable Static Constructor Code //FatherVariable Constructor Code //FatherVariable Constructor Method //父類靜態代碼塊 //Father Static Constructor Code //子類靜態變量 //ChildVariable Static Constructor Code //ChildVariable Constructor Code //ChildVariable Constructor Method //子類靜態代碼塊 //Child Static Constructor Code //父類構造代碼塊 //Father Constructor Code //父類構造方法 //Father Constructor Method //子類構造代碼塊 //Child Constructor Code //子類構造方法 //Child Constructor Method } }
圖解分析
實例化順序
父類靜態變量
↓
父類靜態代碼塊
↓
子類靜態變量
↓
子類靜態代碼塊
↓
父類構造代碼塊
↓
父類構造方法
↓
子類構造代碼塊
↓
子類構造方法
//父類靜態變量 //FatherVariable Static Constructor Code //FatherVariable Constructor Code //FatherVariable Constructor Method //父類靜態代碼塊 //Father Static Constructor Code //子類靜態變量 //ChildVariable Static Constructor Code //ChildVariable Constructor Code //ChildVariable Constructor Method //子類靜態代碼塊 //Child Static Constructor Code //父類構造代碼塊 //Father Constructor Code //父類構造方法 //Father Constructor Method //子類構造代碼塊 //Child Constructor Code //子類構造方法 //Child Constructor Method
結論:
1.帶繼承的類:
先按照聲明順序初始化基類靜態變量和靜態代碼塊,接着按照聲明順序初始化子類靜態變量和靜態代碼塊,
而后按照聲明順序初始化基類普通變量和普通代碼塊,然后執行基類構造函數,接着按照聲明順序初始化子類普通變量和普通代碼塊
最后執行子類構造函數。