java初始化塊(靜態)順序

來源:互聯網
上載者:User
public class Person{{a = 6;//if (a > 4){System.out.println("Person init block a > 4");}}public int a = 9;{System.out.println("second executed");}static {//即使不執行個體化對象也會執行System.out.println("Person static block");}public static void main(String[] args){//Person p = new Person();//System.out.println(" a  " + p.a);Leaf l = new Leaf();Leaf ll = new Leaf();}}class Root{static{System.out.println("root static init");}{System.out.println("root normal init");}public Root(){System.out.println("root constructor");}}class Mid extends Root{static{System.out.println("mid static init");}{System.out.println("mid normal init");}public Mid(){System.out.println("mid constructor");}}class Leaf extends Mid{static{System.out.println("Leaf static init");}{System.out.println("Leaf normal init");}public Leaf(){System.out.println("Leaf constructor");}}

輸出結果為:

Person static block
root static init
mid static init
Leaf static init
root normal init
root constructor
mid normal init
mid constructor
Leaf normal init
Leaf constructor
root normal init
root constructor
mid normal init
mid constructor
Leaf normal init
Leaf constructor

初始化 順序 :

靜態 初始化塊(父類   --->   子類 )---->父類 的 非靜態初始化塊(聲明屬性執行個體預設值 (由初始化塊和預設值定義聲明的順序決定執行順序 ))   ----->  父類的建構函式   ------->   子類的非靜態初始化塊 (聲明屬性執行個體預設值 (由初始化塊和預設值定義聲明的順序決定執行順序 )) --------->   子類的建構函式

聯繫我們

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