静态数据的初始化

无论创建多少个对象,静态数据都只占用一份存储区域。static关键字不能应用于局部变量,因此它只能作用于域。如果一个域是静态的基本类型域,且也没有对它进行初始化,那么就会获得基本类型的标准初值,如果他是一个对象引用,那么它的默认初始值就是null。

/**
* Created by wangw on 2016/2/28.
*/
public class Demo3 {
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);

}
static Table table = new Table();
static Cupboard cupboard = new Cupboard();
}
class Bowl{
Bowl(int marker){
System.out.println("marker==="+marker);
}
void f(int marker){
System.out.println("marker1===="+marker);
}
}
class Table{
static Bowl bowl1 = new Bowl(1);
Table(){
System.out.println("Table");
bowl1.f(1);
}
void f2(int marker){
System.out.println("f2-maker"+marker);
}
static Bowl bowl2 = new Bowl(2);
}
class Cupboard{
Bowl bowl3 = new Bowl(3);
static Bowl bowl4 = new Bowl(4);
Cupboard(){
System.out.println("Cupboard");
bowl4.f(2);
}
void f3(int marker){
System.out.println("f3==marker"+marker);
}
static Bowl bowl5 = new Bowl(5);
}
输出结果:

marker===1
marker===2
Table
marker1====1
marker===4
marker===5
marker===3
Cupboard
marker1====2
Creating new Cupboard in main
marker===3
Cupboard
marker1====2
Creating new Cupboard in main
marker===3
Cupboard
marker1====2
f2-maker1
f3==marker1

初始化的顺序是先静态对象(如果它们尚未因前面的对象创建过程而被初始化),而后是“非静态”对象。



posted @ 2016-02-28 22:39  Roy110  阅读(344)  评论(0编辑  收藏  举报