关于初始化及初始化顺序

成员变量的自动初始化

首先,类的成员变量会被自动初始化,并且会在构造器被调用前发生,如下:

public class TestInitialization {
    //成员变量i
    private int i;

    public TestInitialization() {
        System.out.println(i);//输出0,说明在i被声明时被初始化为0
        System.out.print(i++);//输出1
    }

    public static void main(String[] args) {
        new TestInitialization();
    }

}

静态数据的初始化顺序

代码如下:

//主类
public class StaticInitialization {

    public static void main(String[] args) {
        System.out.println("Creating new Cupboard() in main");
        new Cupboard();
        System.out.println("Creating new Cupboard() in main");
        new Cupboard();
        table.f2(1);
        cupboard.f3(1);
    }

    //调用main之前,顺序初始化两个静态实例
    //若存在非静态引用,则在静态引用被初始化后,继续初始化非静态引用
    static Table table = new Table();

    static Cupboard cupboard = new Cupboard();

}

//bowl
class Bowl {

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

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

}

//table
class Table {

    static Bowl bowl1 = new Bowl(1);

    Table() {
        System.out.println("Table()");
        bowl2.f1(1);
    }

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

    static Bowl bowl2 = new Bowl(2);

}

//cupboard 
class Cupboard {

    //静态引用bowl4、bowl5初始化后,初始化bowl3
    Bowl bowl3 = new Bowl(3);

    static Bowl bowl4 = new Bowl(4);

    Cupboard() {
        System.out.println("Cupboard()");
        bowl4.f1(2);
    }

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

    static Bowl bowl5 = new Bowl(5);

}

输出如下:

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

未完,待整理。。。

发布了9 篇原创文章 · 获赞 7 · 访问量 3191

猜你喜欢

转载自blog.csdn.net/weixin_42806169/article/details/81504802