静态数据的初始化

源码:

package reborn;

class Bowl {

  Bowl(int marker) {

    System.out.println("Bowl(" + marker + ")");

  }

  void f(int marker) {

    System.out.println("f(" + marker + ")");

  }

}

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);

}

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);

}

public class hello {

  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();

    t2.f2(1);

    t3.f3(1);

  }

  static Table t2 = new Table();

  static Cupboard t3 = new Cupboard();

}

输出:

Bowl(1)//初始化table,执行 static Bowl b1 = new Bowl(1);

Bowl(2)// static Bowl b2 = new Bowl(2);

Table()//static数据初始化完才进行真正的类初始化

f(1)

Bowl(4)//同理static Cupboard t3 = new Cupboard();初始化

Bowl(5)

Bowl(3)//非static对象初始化

Cupboard()

f(2)

Creating new Cupboard() in main

Bowl(3)//非static对象每次新建对象都会初始化

Cupboard()

f(2)

Creating new Cupboard() in main

Bowl(3)

Cupboard()

f(2)

f2(1)

f3(1)

static初始化只有在必要的时候才会进行。如果不创建一个Table对象,而且永远都不引用Table.b1或Table.b2,那么static Bowl b1和b2永远都不会创建。然而,只有在创建了第一个Table对象之后(或者发生了第一次static访问),它们才会创建。在那以后,static对象不会重新初始化。

初始化的顺序是首先static(如果它们尚未由前一次对象创建过程初始化),接着是非static对象。大家可从输出结果中找到相应的证据。

在这里有必要总结一下对象的创建过程。

明确的静态初始化:

源程序:


class Cup {

  Cup(int marker) {

    System.out.println("Cup(" + marker + ")");

  }

  void f(int marker) {

    System.out.println("f(" + marker + ")");

  }

}

class Cups {

  static Cup c1;

  static Cup c2;

  static {

    c1 = new Cup(1);

    c2 = new Cup(2);

  }

  Cups() {

    System.out.println("Cups()");

  }

}

public class hello {

  public static void main(String[] args) {

    System.out.println("Inside main()");

    Cups.c1.f(99);  // (1)

  }

  static Cups x = new Cups();  // (2)

static Cups y = new Cups();  // (2)

}

输出:

Cup(1)

Cup(2)

Cups()

Cups()

Inside main()

f(99)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容