变量初始化的顺序问题
看java编程思想,在变量初始化过程中有点绕,摘出来,记录下。
/**
* 定义一个bowl类
*
* @author 吧嘻小米
* @since 1.0-SNAPSHOT
*/
public class Bowl {
public Bowl(int marker) {
System.out.println("Bowl(" + marker + ")");
}
public void f1(int marker) {
System.out.println("f1(" + marker + ")");
}
}
/**
* 定义一个cupboard类
*
* @author 吧嘻小米
* @since 1.0-SNAPSHOT
*/
public class Cupboard {
static Bowl bowl4 = new Bowl(4);
static Bowl bowl5 = new Bowl(5);
Bowl bowl3 = new Bowl(3);
public Cupboard() {
System.out.println("cupboard()");
bowl4.f1(2);
}
public void f3(int marker) {
System.out.println("f3(" + marker + ")");
}
}
/**
* 定义table类
*
* @author 吧嘻小米
* @since 1.0-SNAPSHOT
*/
public class Table {
static Bowl bowl1 = new Bowl(1);
static Bowl bowl2 = new Bowl(2);
public Table() {
System.out.println("Table()");
bowl2.f1(1);
}
public void f2(int marker) {
System.out.println("f2(" + marker + ")");
}
}
/**
* 变量初始化的顺序演示
* * @author 吧嘻小米
* @since 1.0-SNAPSHOT
*/
public class StaticInitialization {
static Table table = new Table();
static Cupboard cupboard = new Cupboard();
public static void main(String[] args) {
System.out.println("create new Cupboard() in main");
new Cupboard();
System.out.println("Create new Cupboard() in main");
new Cupboard();
table.f2(1);
cupboard.f3(1);
}/*Output:
Bowl(1)
Bowl(2)
Table()
f1(1)
Bowl(4)
Bowl(5)
Bowl(3)
cupboard()
f1(2)
create new Cupboard() in main
Bowl(3)
cupboard()
f1(2)
Create new Cupboard() in main
Bowl(3)
cupboard()
f1(2)
f2(1)
f3(1)
*///:~
}
小结:
- 变量的初始化顺序,静态变量–>其他变量;
- 只有当一个变量完成全部的初始化(包括静态变量的初始化,构造方法的完成等)才会顺序执行下一个变量的初始化;
- 静态变量只会初始化一次,非静态变量会被初始化多次;
- 静态变量只有在被调用时才会初始化。