Java类初始化顺序问题:静态初始化块,非静态初始化块以及构造函数

在Java类中,初始化方式有三种:静态初始化块,非静态初始化块和构造函数。这就涉及初始化顺序问题,那么有两个问题:

单个类的初始化顺序是怎样的呢?

当有类继承时,Java类初始化顺序是怎样的呢?

实验代码:

class Super {
	private static int i = getI();
	
	{
		System.out.println("super non-static initalization before");
	}
	
	static {
		System.out.println("super static initalization before");
	}
	
	public Super() {
		System.out.println("super constructor initalization");
	}

	{
		System.out.println("super non-static initalization after");
	}
	
	private static int j = getJ();
	
	static {
		System.out.println("super static initalization after");
	}
	
	private static int getI() {
		System.out.println("super static field before");
		return 0;
	}
	
	private static int getJ() {
		System.out.println("super static field after");
		return 0;
	}
}

class Sub extends Super{
	{
		System.out.println("sub non-static initalization before");
	}
	
	static {
		System.out.println("sub static initalization before");
	}
	
	public Sub( ) {
		System.out.println("sub constructor initalization");
	}
	
	{
		System.out.println("sub non-static initalization after");
	}
	
	static {
		System.out.println("sub static initalization after");
	}
	
}

public class ConstructorTest {
	public static void main(String[] args) {
		Sub s = new Sub();
	}
}

输出结果:

super static field before
super static initalization before
super static field after
super static initalization after
sub static initalization before
sub static initalization after
super non-static initalization before
super non-static initalization after
super constructor initalization
sub non-static initalization before
sub non-static initalization after
sub constructor initalization

实验可知,java类初始化大致顺序归纳为 两条基本原则

1、先静态,后非静态

2、先父类,后子类


具体原则如下:

1、子类静态优先于父类非静态、构造函数

2、先非静态初始化块,后构造函数;相当于把非静态初始块移到构造函数开始处

3、同类型语句按出现顺序进行初始化;这里静态变量静态初始化块是同类型语句,所以按语句先后顺序进行初始化

你可能感兴趣的:(编程语言)