Java基礎知識-對象初始化__Java

來源:互聯網
上載者:User
1. Java對象的初始化順序如下:
   父類 static欄位及 static塊 -> 子類 static欄位及 static塊 
   -> 父類非 static欄位及非 static塊 -> 父類構造方法 
   -> 子類非 static欄位及非 static塊 -> 子類構造方法 
2. 範例程式碼如下:
package org.demo;public class InitDemo {    public static void main(String[] args) {        new Child("init");    }}class Parent {    private static int total = 1;    private int id = print("id");        private static Parent p1 = new Child("child1");    private static Parent p2 = new Child("child2");    private static int i = print("i");    private static int j = 99;    static {        print("靜態塊");    }        {        print("構造塊");    }    public Parent(String str) {        System.out.println("parent, " + (total++) + ":" + str + " i=" + i + " j=" + j);        ++i;        ++j;        System.out.println(toString());    }        public static int print(String str) {        System.out.println("parent, " + (total++) + ":" + str + " i=" + i + " j=" + j);        ++j;        return ++i;    }    public String toString() {        return "parent, total=" + total + " id=" + id;    }}class Child extends Parent {    private static int total = -1;    private int id = -1;        public Child(String name) {        super(name);        if (total < 0) {            total = 1;        } else {            total++;        }        id=total;        System.out.println(toString());    }        public static int print(String str) {        System.out.println(" child, str=" + str);        return 0;    }    public String toString() {        return " child, total=" + total + " id=" + id;    }}/*parent, 1:id i=0 j=0parent, 2:構造塊 i=1 j=1parent, 3:child1 i=2 j=2 child, total=0 id=0 child, total=1 id=1parent, 4:id i=3 j=3parent, 5:構造塊 i=4 j=4parent, 6:child2 i=5 j=5 child, total=1 id=0 child, total=2 id=2parent, 7:i i=6 j=6parent, 8:靜態塊 i=7 j=99parent, 9:id i=8 j=100parent, 10:構造塊 i=9 j=101parent, 11:init i=10 j=102 child, total=-1 id=0 child, total=1 id=1*/
3. 分析如下:

聯繫我們

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