敦化新闻,融通高科驱动,非诚勿扰白鲸驯养师
使用{}
包裹的代码区域,这里的代码区域特指位于class{}
下面的而不是存在于其他type method(){}
这类函数下面的代码区域
public class helloa { /** ... */ { system.out.println("i'm a construct code block"); } }
构造函数代码块指的是构造函数中所包含的代码,类似classname(){}
中的代码块
public class helloa { public helloa(){ system.out.println("i'm a construct method code block"); } }
static代码块指的是static{}
包裹的代码块,且静态代码只执行一次,可以通过class.forname("classpath")
的方式唤醒代码的static代码块,但是也执行一次。
public class helloa { static{ system.out.println("i'm a static code block"); } }
public class helloa { public helloa(){ system.out.println("i'm a construct method code block"); } { system.out.println("i'm a construct code block"); } static { system.out.println("i'm a static code block"); } public static void main(string[] args) { new helloa(); new helloa(); } }
result
i'm a static code block
i'm a construct code block
i'm a construct method code block
i'm a construct code block
i'm a construct method code block
可以看到显示static代码初始化,然后是构造方法初始化,然后是构造函数初始化,并且静态代码只会初始化一次。
这里可以直接代码编译后的文件helloa.class
// // source code recreated from a .class file by intellij idea // (powered by fernflower decompiler) // public class helloa { /*构造代码块直接被内联到了构造函数代码块中*/ public helloa() { system.out.println("i'm a construct code block"); system.out.println("i'm a construct method code block"); } public static void main(string[] args) { new helloa(); new helloa(); } static { system.out.println("i'm a static code block"); } }
因此得出结论构造代码块直接被内联到构造函数代码块中
并且还可以推论可以直接在构造代码块中调用this
或者调用this.method()
或者this.staticmethod()
;
public class hellob extends helloa { { system.out.println("i'm a construct code block"); } public hellob() { system.out.println("i'm a construct method code block"); } static { system.out.println("i'm b static code block"); } public static void main(string[] args) { new hellob(); } }
result
i'm a static code block
i'm b static code block
i'm a construct code block
i'm a construct method code block
i'm a construct code block
i'm a construct method code block
初始化的整体顺序可以渐进的表示为
static > instace
有继承初始化顺序:
https://blog.csdn.net/harryptter/article/details/87875399#%e7%ac%94%e8%af%95%e9%a2%98
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
浅析我对 String、StringBuilder、StringBuffer 的理解
使用IDEA搭建SSM框架的详细教程(spring + springMVC +MyBatis)
Springboot整合freemarker 404问题解决方案
引入mybatis-plus报 Invalid bound statement错误问题的解决方法
网友评论