Java类属性和对象属性的初始化顺序如下:
(1) 类属性(静态变量)定义时的初始化
(2) static块中的初始代码
(3) 对象属性(非静态变量)定义时的初始化
(4) 构造方法(函数)中的初始化代码
下面举例说明:
<pre name="code" class="java">public class test {
//类属性
static String a = "string-a";
static String b;
//对象属性
String c = "string-c";
String d;
//static块
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 = "string-b"
************before constructor****************
a = "string-a"
b = "string-b"
c = "string-c"
d = "null"
************after constructor****************
a = "string-a"
b = "string-b"
c = "string-c"
d = "string -d"
由此可以看出类属性与对象属性的初始化顺序。