1. 程式人生 > >java類載入和例項化:靜態程式碼塊、初始化程式碼塊、構造方法的執行順序

java類載入和例項化:靜態程式碼塊、初始化程式碼塊、構造方法的執行順序

java中第一次例項化一個物件時,靜態程式碼塊、初始化塊、屬性的初始化、構造方法,再加上如果父類也有這些東西,天,到底執行順序是什麼?

來一段程式碼試一試就知道了:

public class LoadingTest {

	public static void main(String[] args) {
		new TestLoading();
	}
}

class TestLoading extends SuperTestLoading {

	private static Integer i = getIntegerI();
	private Integer j = getIntegerJ();

	static {
		System.out.println("子類的靜態程式碼塊");
	}

	{
		System.out.println("子類的初始化程式碼塊");
	}

	TestLoading() {
		System.out.println("子類的構造方法");
	}

	private static Integer getIntegerI() {
		System.out.println("子類的靜態屬性");
		return null;
	}

	private static Integer getIntegerJ() {
		System.out.println("子類的例項屬性");
		return null;
	}
}

class SuperTestLoading {

	protected static Integer superI = getIntegerI();
	protected Integer superJ = getIntegerJ();

	static {
		System.out.println("父類的靜態程式碼塊");
	}

	{
		System.out.println("父類的初始化程式碼塊");
	}

	SuperTestLoading() {
		System.out.println("父類的構造方法");
	}

	private static Integer getIntegerI() {
		System.out.println("父類的靜態屬性");
		return null;
	}

	private static Integer getIntegerJ() {
		System.out.println("父類的例項屬性");
		return null;
	}
}
我在本機的執行結果如下:

之後我自己再通過反覆交換程式碼所在的位置,得出以下執行順序:

父類的靜態程式碼塊、父類的靜態屬性——>子類的靜態程式碼塊、子類的靜態屬性——>父類的初始化程式碼塊、父類的例項屬性——>父類的構造方法——>子類的初始化程式碼塊、子類的例項屬性——>子類的構造方法。

其中順序從前到後,其中用"、"號分隔的兩個都是優先順序相同的,誰先執行看程式碼在類中的位置,靠上的先執行。

基本原則就是:靜態的早於例項的、父類的早於子類的、構造方法最晚。