一段代码看懂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,然后执行父类构造函数,最后执行子类构造函数

你可能感兴趣的:(Java,基础)