ITeye博客

Java 初始化

ericwzc · 2012-07-17 16:06 · 编程语言 · Markdown

public class Base {
	private String s1 = "Base string";
	static int k = 0;
	static {
		System.out.println("Base static block before constructor");
		System.out.println("Base k=" + k);
		k++;
	}
	{
		System.out.println("Base instance block before constructor");
		System.out.println("Base s1= "  + s1);		
		s1 = "Base string2";
	}
	public Base(){
		System.out.println("Base Constructor");		
	}
	{
		System.out.println("Base instance block after constructor");
		System.out.println("Base s1= "  + s1);
	}
	static{
		System.out.println("Base static block after constructor");
		System.out.println("Base k=" + k);
	}	
}

public class Child extends Base {
	private String s1 = "Child string";
	static int k = 0;
	static {
		System.out.println("Child static block before constructor");
		System.out.println("Child k=" + k);
		k++;
	}
	{
		System.out.println("Child instance block before constructor");
		System.out.println("Child s1= "  + s1);		
		s1 = "Child string2";
	}
	public Child(){
		System.out.println("Child Constructor");		
	}
	{
		System.out.println("Child instance block after constructor");
		System.out.println("Child s1= "  + s1);
	}
	static{
		System.out.println("Child static block after constructor");
		System.out.println("Child k=" + k);
	}
	public static void main(String[] args){
		new Child();
	}
}

 

结果:

Base static block before constructor
Base k=0
Base static block after constructor
Base k=1
Child static block before constructor
Child k=0
Child static block after constructor
Child k=1
Base instance block before constructor
Base s1= Base string
Base instance block after constructor
Base s1= Base string2
Base Constructor
Child instance block before constructor
Child s1= Child string
Child instance block after constructor
Child s1= Child string2
Child Constructor

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。