首页 > 代码库 > Java初始化顺序

Java初始化顺序

1、在类的内部,变量的定义的先后顺序决定了初始化顺序,即使变量定义散布于方法定义间,他们仍旧会在任何方法(包括构造器)被调用之前得到初始化

2、静态数据的初始化

class Bowl{
Bowl(int marker){
print("Bowl("+marker+")");
}
void f1(int marker){
print("f1("+marker+")");
}

class Table{
static Bowl bowl1=new Bowl(1);
Table(){
print("Table()");
bowl2.f1(1);
}
void f2(int marker){
print("f2("+marker+")");
}
static Bowl bowl2=new Bowl(2);
}
}

class Cupboard{
Bowl bowl3=new Bowl(3);
static Bowl bowl4=new Bowl(4);

Cupboard(){
print("Cupboard()");
bowl4.f1(2);
}
void f3(int marker){
print("f3("+marker+")");
}
static Bowl bowl5=new Bowl(5);
}

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

static Table table=new Table();
static Cupboard cupboard=new Cupboard();
}

output:

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)


3、显式的静态初始化

class Cup{
Cup(int marker){print("Cup("+marker+")");}
void f(int marker){print("f("+marker+")");}
}

class Cups{
static Cup cup1;
static Cup cup2;
static {
cup1=new Cup(1);
cup2=new Cup(2);
}

Cups(){
print("Cups()");
}

public class ExlicitStatic{
public static void main(String args[]){
print("Inside main()");
Cups.cup1.f(99);   //(1)
}

//static Cups cup1=new Cup();  //(2)
//static Cups cup2=new Cup();  //(2)
}
}

output:

Cup(1)

Cup(2)

f(99)