`
ericwzc
  • 浏览: 12042 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

Java 初始化

 
阅读更多
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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics