Java知識積累——靜態代碼塊,非靜態代碼塊,構造器的執行順序和次數

來源:互聯網
上載者:User

看如下程式

 1 class A { 2    static{ 3       System.out.println("A static"); 4    }    5  6    { 7       System.out.println("A not static");  8    }    9 10    public A(){11       System.out.println("A new");12    }13 }14 15 class B extends A{16    static{17       System.out.println("B static");18    }   19 20    {21       System.out.println("B not static"); 22    }  23 24    public B(){25       System.out.println("B new");26    }27 } 28 29 public class MainTest {30    public static void main(String[] args) {31       A ab= new B();32       ab= new B();33    }34 }

輸出如下:

A static

B static

A not static

A new

B not static

B new

A not static

A new

B not static

B new

 

結論: 

靜態代碼塊只有類首次載入進記憶體時調用一次,只此一次。

非靜態代碼塊,每次建立對象時,會在建構函式之前被調用。

建構函式,每次建立對象時,最後調用。

建立子類對象時,先建立父類對象,再建立子類對象。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.