1. 程式人生 > >一段程式碼看懂Java類的載入和初始化

一段程式碼看懂Java類的載入和初始化

先貼程式碼

class Base {
	int a = numa();  
	private static int c = numc(); 
	static int b = numb();
	static {
		System.out.println("Base:static code block..");  
	}
	Base(){
		System.out.println("Base:constructor..."); 
	}

	static int numa(){
		System.out.println("Base:int a..."); 
		return 1;
	}
	static int numb(){
		System.out.println("Base:static int b...");
		return 1;
	}
	static int numc(){
		System.out.println("Base:private static int c...");
		return 1;
	}
}

class A extends Base{  
	private static int l = numl();
	private int m = numm();
	static{  
		System.out.println("A:static code block...");
	}
	A(){  
		System.out.println("A:constructor..."); 
	}   
	static int numl() {  
		System.out.println("A:static int l...");  
		return 1;  
	}  
	int numm() {  
		System.out.println("A:private int m...");  
		return 1;  
	}

}

public class Test{
	public static void main(String[] args){
		new A();
	}
}

輸出結果如下:

Base:private static int c...
Base:static int b...
Base:static code block..
A:static int l...
A:static code block...
Base:int a...
Base:constructor...
A:private int m...
A:constructor...


從輸出結果很直觀的看出初始化的順序。靜態到例項,父類到子類,例項化的時候構造器就開始工作了。

總結:先載入父類,再載入子類,然後初始化父類static,然後初始化子類static,然後執行父類建構函式,最後執行子類建構函式