一个例子: public class Test {
static String a = "string-a";
static String b;
String c = "stirng-c";
String d;
static {
printStatic("before static");
b = "string-b";
printStatic("after static");
}
public static void printStatic(String title) {
System.out.println("---------" + title + "---------");
System.out.println("a = \"" + a + "\"");
System.out.println("b = \"" + b + "\"");
}
public Test() {
print("before constructor");
d = "string-d";
print("after constructor");
}
public void print(String title) {
System.out.println("---------" + title + "---------");
System.out.println("a = \"" + a + "\"");
System.out.println("b = \"" + b + "\"");
System.out.println("c = \"" + c + "\"");
System.out.println("d = \"" + d + "\"");
}
public static void main(String[] args) {
new Test();
}
}
运行结果:
-----------before static-----------
a = "string-a"
b = "null"
-----------after static-----------
a = "string-a"
b = "static-b"
-----------before constructor-----------
a = "string-a"
b = "static-b"
c = "string-c"
d = "null"
-----------after constructor-----------
a = "string-a"
b = "static-b"
c = "string-c"
d = "string-d"
结果分析:
由这个例子可以看出Java类属性和对象属性的初始化顺序如下
1 类属性(静态变量)定义时的初始化,如范例中的 static String a = "string-a"
2 static块中的初始化代码,如范例中的 static{} 中的 b = "string-b"
3 对象属性(非静态变量)定义时的初始化,如范例中的 String c = "string-c"
4 构造方法(函数)中的初始化代码,如范例构造方法中的 d = "string-d"
代码出处:《Java从入门到精通》