java初始化

public class InitObjectDemo extends Base{
	int derive_i;
	static int s_derive_i = 4;
	static{ //静态初始化块
		static_print();
		System.out.println("derive class: static{}");
	}
	{//实例初始化块
		instances_print();
		static_print();
		System.out.println("derive class instanc init()");
	}
	public InitObjectDemo(){
		System.out.println("derive_i=" + derive_i);
		System.out.println("static_derive_i=" + s_derive_i);
	}
	public  void instances_print(){
		System.out.println("derive_class:instances function call");
	}
	public  void base_instances_print(){
		System.out.println("base_derive_class:instances function call");
	}
	public static void static_print(){
		System.out.println("derive_class:static function call");
	}
	public static void main(String[] args){
		new InitObjectDemo();
		new InitObjectDemo();
	}
 
}
 
class Base{
	int base_i;
	static int s_base_i = 2;
	static{ //静态初始化块
		static_print();
		System.out.println("base class: static{}");
	}
	{ //实例初始化块
		base_instances_print();//调用的方法是子类中覆盖基本的方法,
		this_instances_print();  
		static_print();
		System.out.println("base class instanc init()");
	}
	public  void this_instances_print(){
		System.out.println("base_class:instances function call");
	}
	public  void base_instances_print(){
		System.out.println("base_class:instances function call");
	}
	public static void static_print(){
		System.out.println("base_class:static function call");
	}
	public Base(){
		System.out.println("base_i=" + base_i);
		System.out.println("static_base_i=" + s_base_i);
	}
}

 

 

输出:
base_class:static function call
base class: static{}
derive_class:static function call
derive class: static{}
base_derive_class:instances function call
base_class:instances function call
base_class:static function call
base class instanc init()
base_i=0
static_base_i=2
derive_class:instances function call
derive_class:static function call
derive class instanc init()
derive_i=0
static_derive_i=4
base_derive_class:instances function call
base_class:instances function call
base_class:static function call
base class instanc init()
base_i=0
static_base_i=2
derive_class:instances function call
derive_class:static function call
derive class instanc init()
derive_i=0
static_derive_i=4

1. 初始化过程
初始化顺序:
第一次创建对象的时候:
1. 先递归执行父类的静态初始化块,然后执行子类的静态初始化块;
2. 先递归执行父类的实例初始化块,然后执行父类的构造方法;
3. 执行子类的实例初始化块,然后执行子类的构造方法;
第二次创建对象的时候:
4. 如果父类的静态初始化块已经执行过,则跳过;否则递归执行父类的静态初始化块,然后执行子类的静态初始化块;
5. 先递归执行父类的实例初始化块,然后执行父类的构造方法;
6. 执行子类的实例初始化块,然后执行子类的构造方法;

你可能感兴趣的:(java)