1. Java對象的初始化順序如下:
父類
static欄位及
static塊 -> 子類
static欄位及
static塊
-> 父類非
static欄位及非
static塊 -> 父類構造方法
-> 子類非
static欄位及非
static塊 -> 子類構造方法
2. 範例程式碼如下:
package org.demo;public class InitDemo { public static void main(String[] args) { new Child("init"); }}class Parent { private static int total = 1; private int id = print("id"); private static Parent p1 = new Child("child1"); private static Parent p2 = new Child("child2"); private static int i = print("i"); private static int j = 99; static { print("靜態塊"); } { print("構造塊"); } public Parent(String str) { System.out.println("parent, " + (total++) + ":" + str + " i=" + i + " j=" + j); ++i; ++j; System.out.println(toString()); } public static int print(String str) { System.out.println("parent, " + (total++) + ":" + str + " i=" + i + " j=" + j); ++j; return ++i; } public String toString() { return "parent, total=" + total + " id=" + id; }}class Child extends Parent { private static int total = -1; private int id = -1; public Child(String name) { super(name); if (total < 0) { total = 1; } else { total++; } id=total; System.out.println(toString()); } public static int print(String str) { System.out.println(" child, str=" + str); return 0; } public String toString() { return " child, total=" + total + " id=" + id; }}/*parent, 1:id i=0 j=0parent, 2:構造塊 i=1 j=1parent, 3:child1 i=2 j=2 child, total=0 id=0 child, total=1 id=1parent, 4:id i=3 j=3parent, 5:構造塊 i=4 j=4parent, 6:child2 i=5 j=5 child, total=1 id=0 child, total=2 id=2parent, 7:i i=6 j=6parent, 8:靜態塊 i=7 j=99parent, 9:id i=8 j=100parent, 10:構造塊 i=9 j=101parent, 11:init i=10 j=102 child, total=-1 id=0 child, total=1 id=1*/3. 分析如下: