Java类中静态代码块、结构代码块、构造函数快速理解

Java类中静态代码块、构造代码块、构造函数快速理解

 

package com.test;

public class Son extends Father{
	static{
		System.out.println("Son:静态代码块");
	}
	{
		System.out.println("Son:构造代码块");
	}
	public Son(){
		System.out.println("Son:构造函数");
	}
	public Son(String s){
		super(s);
		System.out.println("Son:构造函数" + s);
	}
	public static void main(String[] args) {
		System.out.println();
		Father fa = new Son("Son");
	}
}

 

package com.test;

public class Father {
	static{
		System.out.println("Father:静态代码块");
	}
	{
		System.out.println("Father:构造代码块");
	}
	public Father(){
		System.out.println("Father:构造函数");
	}
	public Father(String s){
		System.out.println("Father:构造函数" + s);
	}
}

 

执行结果:
Father:静态代码块
Son:静态代码块

Father:构造代码块
Father:构造函数Son
Son:构造代码块
Son:构造函数Son

 

得出结论:

 

1、执行顺序:静态代码块>构造代码块>构造函数。

 

2、静态代码块随类的声明而执行,而构造代码块和构造函数在一个类实例化后执行,其中构造代码块又优先于构造函数代码块。

3、子类没有用super(s)时,默认调用的是父类的无参构造函数块。