静态块,构造块执行顺序

package demo;

public class Test01 {
	public static Test01 t1 = new Test01();
	{
		System.out.println("A");
	}
	static 
	{
		System.out.println("B");
	}
	public static void main(String[] args) {
		Test01 t2 = new Test01();
	}
}

上述代码的执行顺序为:A B A

静态块:用static申明,JVM加载类时执行,仅执行一次 

构造块:类中直接用{}定义,每一次创建对象时执行 

执行顺序优先级:静态块>main()>构造块>构造方法 

注意:不要把    public static Test01 t1 = new Test01();
                          {
                            System.out.println("A");
                          }

看为一体,有分号。

所以上面代码执行顺序为: JVM加载进Test01类的时候,按顺序执行,遇到了public static Test01 t1 = new Test01(); 输出A

接着,静态块执行:B,再接着mian函数执行,去到勒种调用构造块输出A

发布了159 篇原创文章 · 获赞 86 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_40301026/article/details/95078889
今日推荐