構(gòu)造方法的初始化順序

字號(hào):

想像一下你正在用java寫程序,并且用下面的代碼初始化類 A 和 B 的對(duì)象:
    class A {
    int a = f();
    int f() {
    return 1;
    }
    }
    class B extends A {
    int b = a;
    int f() {
    return 2;
    }
    }
    public class CtorDemo1 {
    public static void main(String args[]) {
    B bobj = new B();
    System.out.println(bobj.b);
    }
    }
    現(xiàn)在,好像很明顯的當(dāng)初始化完成后,bobj.b的值將是1。畢竟,類B中的b 的值是用類A中的a的值初始化的,而a 是用f 的值初始化的,而它的值為1,對(duì)嗎?
    實(shí)際上, bobj.b 的值是2,要知道為什么需要知道對(duì)象初始化的問(wèn)題。
    當(dāng)一個(gè)對(duì)象被創(chuàng)建時(shí),初始化是以下面的順序完成的:
    1. 設(shè)置成員的值為缺省的初始值 (0, false, null)
    2. 調(diào)用對(duì)象的構(gòu)造方法 (但是還沒(méi)有執(zhí)行構(gòu)造方法體)
    3. 調(diào)用父類的構(gòu)造方法
    4. 使用初始化程序和初始?jí)K初始化成員
    5. 執(zhí)行構(gòu)造方法體
    看看在實(shí)際中是如何一步一步完成的,看看下面的例子:
    class A {
    A() {
    System.out.println("A.A called");
    }
    }
    class B extends A {
    int i = f();
    int j;
    {
    j = 37;
    System.out.println("initialization block executed");
    }
    B() {
    System.out.println("B.B called");
    }
    int f() {
    System.out.println("B.f called");
    return 47;
    }
    }
    public class CtorDemo2 {
    public static void main(String args[]) {
    B bobj = new B();
    }
    }