關於java中普通代碼塊、構造代碼塊與靜態代碼塊,java構造代碼靜態

來源:互聯網
上載者:User

關於java中普通代碼塊、構造代碼塊與靜態代碼塊,java構造代碼靜態

1.普通代碼塊

public static void main(String[] args) {
/*普通代碼塊:
*直接定義在在方法或語句中出現”{普通代碼的執行語句}“的就稱為普通代碼塊。
*普通代碼塊執行順序由他們在代碼中出現的次序決定--“先出現先執行”
* */
{
  System.out.println("這裡是普通代碼塊A");
}
//new A();
{
  System.out.println("這裡是普通代碼塊B");
}
}

執行結果:這裡是普通代碼塊A
     這裡是普通代碼塊B

2.靜態代碼塊與構造代碼塊

在java中使用static關鍵字聲明的代碼塊。常用於對類的初始化,每個靜態代碼塊只會執行一次(類在記憶體中載入時執行,類在記憶體中載入後類已經存在)由於JVM在載入類時會執行靜態代碼塊,所以靜態代碼塊先於主方法執行。如果類中包含多個靜態代碼塊,那麼將按照"先定義的代碼先執行,後定義的代碼後執行。

ps:1 靜態代碼塊不能存在於任何方法體內。2 靜態代碼塊不能直接存取靜態執行個體變數和執行個體方法,需要通過類的執行個體對象來訪問。
構造塊:直接在類中定義且沒有加static關鍵字的代碼塊稱為{}構造代碼塊。構造代碼塊在建立對象時被調用,每次建立對象都會被調用,並且構造代碼塊的執行次序優先於類建構函式。

public class structure {
{
System.out.println("這裡是普通代碼塊");//所有類中有一個預設的建構函式,這裡的代碼塊為構造代碼塊,在類中的對象被建立時執行
}
public static void main(String[] args) {

/*普通代碼塊:
*直接定義在在方法或語句中出現”{普通代碼的執行語句}“的就稱為普通代碼塊。
*普通代碼塊執行順序由他們在代碼中出現的次序決定--“先出現先執行”
* */
{
System.out.println("這裡是普通代碼塊A");
}
new structure();//第二次類載入時靜態代碼塊不執行
//new A();
{
System.out.println("這裡是普通代碼塊B");
}
}

static{
System.out.println("這裡是靜態代碼塊");
}
}

執行結果:

這裡是靜態代碼塊//優先於主函數
這裡是普通代碼塊A
這裡是普通代碼塊//類中的對象被建立時執行,每建立一次執行一次,在加一句new structure(); 執行結果為:              

這裡是普通代碼塊B

3.概要總結

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("這裡是靜態代碼塊");
}
}
class A{
static{
System.out.println("這裡是A中的普靜態代碼塊1");
}
{
System.out.println("這裡是A中的普通代碼塊1");
}
{
System.out.println("這裡是A中的普通代碼塊2");
}

}

執行結果:

這裡是靜態代碼塊
這裡是普通代碼塊A
這裡是A中的普靜態代碼塊1
這裡是A中的普通代碼塊1
這裡是A中的普通代碼塊2
這裡是普通代碼塊B

優先順序總結:靜態代碼塊>Main()>構造代碼塊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.