关于java中普通代码块、构造代码块与静态代码块
1.普通代碼塊
public static void main(String[] args) {
/*普通代碼塊:
*直接定義在在方法或語句中出現(xiàn)”{普通代碼的執(zhí)行語句}“的就稱為普通代碼塊。
*普通代碼塊執(zhí)行順序由他們在代碼中出現(xiàn)的次序決定--“先出現(xiàn)先執(zhí)行”
* */
{
System.out.println("這里是普通代碼塊A");
}
//new A();
{
System.out.println("這里是普通代碼塊B");
}
}
執(zhí)行結(jié)果:這里是普通代碼塊A
這里是普通代碼塊B
2.靜態(tài)代碼塊與構(gòu)造代碼塊
在java中使用static關(guān)鍵字聲明的代碼塊。常用于對類的初始化,每個靜態(tài)代碼塊只會執(zhí)行一次(類在內(nèi)存中加載時執(zhí)行,類在內(nèi)存中加載后類已經(jīng)存在)由于JVM在加載類時會執(zhí)行靜態(tài)代碼塊,所以靜態(tài)代碼塊先于主方法執(zhí)行。如果類中包含多個靜態(tài)代碼塊,那么將按照"先定義的代碼先執(zhí)行,后定義的代碼后執(zhí)行。
ps:1 靜態(tài)代碼塊不能存在于任何方法體內(nèi)。2 靜態(tài)代碼塊不能直接訪問靜態(tài)實例變量和實例方法,需要通過類的實例對象來訪問。構(gòu)造塊:直接在類中定義且沒有加static關(guān)鍵字的代碼塊稱為{}構(gòu)造代碼塊。構(gòu)造代碼塊在創(chuàng)建對象時被調(diào)用,每次創(chuàng)建對象都會被調(diào)用,并且構(gòu)造代碼塊的執(zhí)行次序優(yōu)先于類構(gòu)造函數(shù)。
public class structure {
{
System.out.println("這里是普通代碼塊");//所有類中有一個默認(rèn)的構(gòu)造函數(shù),這里的代碼塊為構(gòu)造代碼塊,在類中的對象被創(chuàng)建時執(zhí)行
}
public static void main(String[] args) {
/*普通代碼塊:
*直接定義在在方法或語句中出現(xiàn)”{普通代碼的執(zhí)行語句}“的就稱為普通代碼塊。
*普通代碼塊執(zhí)行順序由他們在代碼中出現(xiàn)的次序決定--“先出現(xiàn)先執(zhí)行”
* */
{
System.out.println("這里是普通代碼塊A");
}
new structure();//第二次類加載時靜態(tài)代碼塊不執(zhí)行
//new A();
{
System.out.println("這里是普通代碼塊B");
}
}
static{
System.out.println("這里是靜態(tài)代碼塊");
}
}
執(zhí)行結(jié)果:
這里是靜態(tài)代碼塊//優(yōu)先于主函數(shù)
這里是普通代碼塊A
這里是普通代碼塊//類中的對象被創(chuàng)建時執(zhí)行,每創(chuàng)建一次執(zhí)行一次,在加一句new structure(); 執(zhí)行結(jié)果為: ? ? ? ? ? ? ?
這里是普通代碼塊B
3.概要總結(jié)
public class structure {
{
System.out.println("這里是普通代碼塊");
}
public static void main(String[] args) {
{
System.out.println("這里是普通代碼塊A");
}
//new structure();
//new structure();
new A();
{
System.out.println("這里是普通代碼塊B");
}
}
static{
System.out.println("這里是靜態(tài)代碼塊");
}
}
class A{
static{
System.out.println("這里是A中的普靜態(tài)代碼塊1");
}
{
System.out.println("這里是A中的普通代碼塊1");
}
{
System.out.println("這里是A中的普通代碼塊2");
}
}
執(zhí)行結(jié)果:
這里是靜態(tài)代碼塊
這里是普通代碼塊A
這里是A中的普靜態(tài)代碼塊1
這里是A中的普通代碼塊1
這里是A中的普通代碼塊2
這里是普通代碼塊B
優(yōu)先級總結(jié):靜態(tài)代碼塊>Main()>構(gòu)造代碼塊
轉(zhuǎn)載于:https://www.cnblogs.com/netlws/p/5728346.html
總結(jié)
以上是生活随笔為你收集整理的关于java中普通代码块、构造代码块与静态代码块的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Maven3教程】Maven多工程、多
- 下一篇: 分布式 Socket 通信