Java中关于static关键字的思考

327 阅读1分钟

群友分享了一到面试题,问代码的执行顺序

执行结果是: 2 3 a=110,b=0 1 4

那么为什么是这样的呢? 这道面试题,其实考察的是static关键字的理解。 简单总结来说:静态块是按顺序执行的,构造代码块总是在于构造器之前执行。

下面是对代码进行断点调试的执行顺序进行标记

public class MagimaTest {
	public static void main(String[] args) {// 13
		magimaFunction();// 10
	}

	static MagimaTest st = new MagimaTest();// 1   7
	static {// 9
		System.out.println("1");// 8
	}
	{
		System.out.println("2");// 2
	}

	MagimaTest() {// 6
		System.out.println("3");// 4
		System.out.println("a=" + a + ",b=" + b);// 5
	}

	public static void magimaFunction() {// 12
		System.out.println("4");// 11
	}

	int a = 110;// 3
	static int b = 112;// 9
}