在《Java编程思想》95页中介绍了静态数据的初始化,并赋有以下代码展示初始化的优先顺序:
public class TestPage95 {
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("Bowl("+marker+")");
}
void f1(int marker){
System.out.println("f1("+marker+")");
}
}
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);
}
class Cupboard{
int aaa=5601;
Bowl bowl3=new Bowl(3);
static Bowl bowl4=new Bowl(4);
Cupboard(){
System.out.println("Cupboard()"+aaa);
bowl4.f1(2);
}
void f3(int marker){
System.out.println("f3("+marker+")");
}
static Bowl bowl5=new Bowl(5);
}
1、在类TestPage95中,静态的对象(Table(),Cupboard())优先于静态的main方法执行;
2、在类Cupboard中,先执行了静态对象,再执行普通对象及字段的初始化,最后执行构造器;
3、new对象会重新执行普通对象及字段的初始化,以及构造器的初始化,而静态初始化只在对象首次加载后进行,之后不再进行;
因而输出结果是:
Bowl(1)
Bowl(2)
Table()
f1(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()5601
f1(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()5601
f1(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()5601
f1(2)
f2(1)
f3(1)
最后在网上找到一个蛮详细关于static的博客,跟大家共享下:
静态对象