順序
1. 父類中靜態成員變量和靜態代碼塊java
2. 子類中靜態成員變量和靜態代碼塊函數
3. 父類中普通成員變量和代碼塊,父類的構造函數測試
4. 子類中普通成員變量和代碼塊,子類的構造函數ui
其中「和」字兩端的按照代碼前後順序執行。spa
舉例
先看代碼:.net
Father類debug
- public class Father {
- public String fStr1 = "father1";
- protected String fStr2 = "father2";
- private String fStr3 = "father3";
-
- {
- System.out.println("Father common block be called");
- }
-
- static {
- System.out.println("Father static block be called");
- }
-
- public Father() {
- System.out.println("Father constructor be called");
- }
-
- }
首先是Father類,該類有一個默認構造函數,有一個static的代碼塊,爲了方便查看結果,還有一個普通代碼塊。
Son類blog
- package com.zhenghuiyan.testorder;
-
- public class Son extends Father{
- public String SStr1 = "Son1";
- protected String SStr2 = "Son2";
- private String SStr3 = "Son3";
-
- {
- System.out.println("Son common block be called");
- }
-
- static {
- System.out.println("Son static block be called");
- }
-
- public Son() {
- System.out.println("Son constructor be called");
- }
-
- public static void main(String[] args) {
- new Son();
- System.out.println();
- new Son();
- }
-
- }
Son類的內容與Father類基本一致,不一樣在於Son繼承自Father。該類有一個main函數,僅爲了測試用,不影響結果。
在main函數中實例化Son。繼承
結果爲:ip
- Father static block be called
- Son static block be called
- Father common block be called
- Father constructor be called
- Son common block be called
- Son constructor be called
-
- Father common block be called
- Father constructor be called
- Son common block be called
- Son constructor be called
總結:
1,在類加載的時候執行父類的static代碼塊,而且只執行一次(由於類只加載一次);
2,執行子類的static代碼塊,而且只執行一次(由於類只加載一次);
3,執行父類的類成員初始化,而且是從上往下按出現順序執行(在debug時能夠看出)。
4,執行父類的構造函數;
5,執行子類的類成員初始化,而且是從上往下按出現順序執行。
6,執行子類的構造函數。