JAVA类代码块执行顺序、以及继承父类的执行顺序

/**
 * Java类代码块执行顺序
 * @author 
 * @date 2017-6-27
 */
public class Sub extends Parent{

	// 静态变量
	//static int a = 0;

	// 非静态代码块
	{
		System.out.println("a:" + a); //打印父类的a
		System.out.println("Sub.scope is running");
		a = 10;
	}
    
	static void staticMethod(){
		System.out.println("Sub static method.a :" + a);
		
	}
	
	// 静态代码块
	static {
		System.out.println("a:" + a);//打印父类的a
		System.out.println("Sub.static scope is running");
		a = 20;
	}

	// 构造函数
	public Sub() {
		System.out.println("Sub.Constructor is running");
	}
	
	public static void main(String arg[]) {
		System.out.println("a:" + Sub.a);
		//由上:先执行父类的相关代码,如果有静态初始化,先执行静态初始化,且只执行一次,以后即使有该类实例化,也不会再执行
		System.out.println("-------------1--------------");
		
		System.out.println("a:" + Sub.a);
		//由上:java中静态代码块首先被执行,且只被执行一次,当实例化一个对象之后,将会首先执行非静态代码块,接着执行构造函数。
		System.out.println("-------------2--------------");		
		
		Sub b1 = new Sub();
		//由上:先执行父类的相关代码,非静态代码块和构造方法
		System.out.println("-------------3--------------");
		
		Sub b2 = new Sub();	
		System.out.println("-------------4--------------");
		System.out.println("a:" + b1.a);
		//由上:打印的是a = 10;
		System.out.println("a:" + b2.a);
		
		System.out.println("-------------5--------------");
		System.out.println("a:" + Sub.a);
		//由上:打印的是a = 10;
		
		System.out.println("-------------6--------------");
		staticMethod();
		//由上:子类重写父类的方法,父类的此方法不会执行
	}
}

class Parent{
	// 静态变量
	static int a = 1;

	// 非静态代码块
	{
		System.out.println("Parent.scope is running");
		a = 100;
	}
    
	static void staticMethod(){
		//子类重写父类的方法,父类的此方法不会执行
		System.out.println("Parent static method.a :" + a);		
	}
	
	// 静态代码块
	static {
		System.out.println("Parent.static scope is running");
		a = 200;
	}

	// 构造函数
	public Parent() {
		System.out.println("Parent.Constructor is running");
	}
}

运行结果:

Parent.static scope is running
a:200
Sub.static scope is running
a:20
-------------1--------------
a:20
-------------2--------------
Parent.scope is running
Parent.Constructor is running
a:100
Sub.scope is running
Sub.Constructor is running
-------------3--------------
Parent.scope is running
Parent.Constructor is running
a:100
Sub.scope is running
Sub.Constructor is running
-------------4--------------
a:10
a:10
-------------5--------------
a:10
-------------6--------------
Sub static method.a :10

当一个类从被JVM装载开始,各种代码的执行顺序大致如下:

被JVM装载->执行父类的相关代码->如果有静态初始化,先执行静态初始化,且只执行一次,以后即使有该类实例化,也不会再执行->如果有静态代码块,以与静态初始化一样的方式执行->如果有new语句带来的实例化,先为成员变量分配空间,并绑定参数列表,隐式或显式执行super(),即父类的构造方法,->执行非静态代码块-〉执行本类的构造函数-〉执行其他代码


你可能感兴趣的:(My,Java,life)