(一)成员初始化过程
1.java类中成员变量的初始化顺序只与定义他们的顺序相同
2.在初始化过程中,成员初始化块与成员变量的初始化处于同等地位,初始化顺序只与定义他们的顺序相同。
非静态实例的初始化块,可以用来保证无论调用了哪个构造器,某些操作总会发生
(二)静态初始化过程
1.java中静态成员变量的初始化过程是在类加载过程中进行的,只要类被使用(申明不算,只包含创建对象,使用类中的方法或成员),其中的静态成员变量会被执行初始化过程。
2.初始化的顺序与他们定义的顺序相同。
比如说如下代码,程序会在SS调用fun()时,先加载SS类,然后初始化SS类中的静态成员变量和静态初始化块,最后才调用fun的方法体。
/**
* Created by wm on 14-9-28.
*/
public class StaticTest {
//static SS ss=new SS();
public static void main(String[] args) {
// System.out.println("ok");
new SS().fun();
}
}
class SS{
static {
System.out.println("static block before");
}
static QQ qq=new QQ("static");
QQ filedQQ=new QQ("filed");
static {
System.out.println("static block after");
}
public SS(){
System.out.println("ss");
}
public static void fun(){
System.out.println("fun");
}
}
class QQ{
public QQ(String str){
System.out.println(str+" qq");
}
}
另附thinking in java中的代码帮助理解
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 {
static {
System.out.println("first");
}
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)
*///:~