首页 > 代码库 > Java编程思想笔记-类的初始化顺序

Java编程思想笔记-类的初始化顺序

1、如果有父类,先初始化父类,然后初始化子类

2、先初始化静态成员变量、静态代码块(static { }包围的代码),然后初始化非静态成员变量、非静态代码块(大括号包围的代码)。静态成员变量间、非静态成员变量间按定义顺序初始化。

3、调用构造函数

class Bowl {
    Bowl(int marker) {
        System.out.println("Bowl(" + marker + ")");
    }

    void f(int marker) {
        System.out.println("f(" + marker + ")");
    }
}

class Cupboard {
    Bowl b3 = new Bowl(3);
    static Bowl b4 = new Bowl(4);

    Cupboard() {
        System.out.println("Cupboard()");
        b4.f(2);
    }

    void f3(int marker) {
        System.out.println("f3(" + marker + ")");
    }

    static Bowl b5 = new Bowl(5);
}

class Table {
    static Bowl b1 = new Bowl(1);

    Table() {
        System.out.println("Table()");
        b2.f(1);
    }

    void f2(int marker) {
        System.out.println("f2(" + marker + ")");
    }

    static Bowl b2 = new Bowl(2);
}

public class Test {

    public static void main(String[] args) throws InterruptedException {

        System.out.println("Creating new Cupboard() in main");
        new Cupboard();
        System.out.println("Creating new Cupboard() in main");
        new Cupboard();
        t2.f2(1);
        t3.f3(1);

    }

    static Table t2 = new Table();
    static Cupboard t3 = new Cupboard();

}

1、开始运行,jvm先加载Test类,此时会初始化静态成员变量  t2、t3

2、然后加载Table类,并初始化该类静态成员变量b1、b2,调用Bowl构造 函数生成对象

3、调用Table构造函数,生成t2对象

4、加载Cupboard类,初始化静态成员变量b4、b5,然后非静态成员变量 b3,并调用Bowl构造函数

5、调用Cupboard构造函数,生成t3对象

6、运行main函数

7、运行 new Cupboard,此时Cupboard已加载入内存,静态成员变量不会再初始化,但非静态成员变量仍然再初始化一次

运行结果:

Bowl(1)
Bowl(2)
Table()
f(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f(2)
f2(1)
f3(1)

  

 

Java编程思想笔记-类的初始化顺序