---
title: "Java 初始化"
author: "ericwzc"
date: "2012-07-17T16:06:08Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2012-07-17T16:06:08Z"
id: 1596497
url: "https://ericwzc.iteye.com/blog/1596497"
---

```
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