在实际的工做过程当中,几乎从没用过JAVA的代码块。不过既然作了这方面的学习与测试,就索性记录下来防止忘记。同一个招式,圣斗士是不会学习第二遍的... java
首先,上代码: 函数
public class CodeBlockTest { public CodeBlockTest(){ //构造函数代码块 System.out.println("this is construct!"); { System.out.println("this is construct code block!"); } } //静态代码块 static{ System.out.println("this is static code block!"); } //普通代码块 { System.out.println("this is code block!"); } @SuppressWarnings("unused") public static void main(String[] args){ { System.out.println("你会不会突然的出现..?"); } CodeBlockTest cbt = null; { System.out.println("在街角的咖啡店..?"); } cbt = new CodeBlockTest(); } }
直接右键运行,测试结果以下: 学习
this is static code block!
你会不会突然的出现..?
在街角的咖啡店..?
this is code block!
this is construct!
this is construct code block! 测试
从输出的结果来看,静态代码块应该是在类加载的时候就开始执行,普通代码块则在类实例化以后第一时间执行,以后是构造函数,构造函数代码块。。。 this
接下来引入子类: spa
public class SonCodeBlockTest extends CodeBlockTest{ public SonCodeBlockTest(){ System.out.println("This is son construct!"); } static{ System.out.println("This is son static block!"); } @SuppressWarnings("unused") public static void main(String[] args){ SonCodeBlockTest son = new SonCodeBlockTest(); } }
this is static code block!
This is son static block!
this is code block!
this is construct!
this is construct code block!
This is son construct! code
很明显,因为类的加载顺序,执行顺序是:父类的静态代码块-->子类的静态代码块-->父类的普通代码块-->父类的构造函数-->子类的普通代码块(若是有的话)-->子类的构造函数 class