java静态数据初始化
https://www.cnblogs.com/zhanghuaze/p/10715931.html
Java中无论创建多少对象,静态数据都只占一份存储区域。
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。Bowl.java:
public class Bowl {
Bowl(int marker) {
System.out.println("Bowl ("+marker+")");
}
void f1(int marker) {
System.out.println("f1 ("+marker+")");
}
}
Table.java:
public class Table {
static Bowl bowl1 = new Bowl(1);
Table(){
System.out.println("Table()");
bowl2.f1(1);
}
void f2(int marker) {
System.out.println("f2 ("+marker+")");
}
static Bowl bowl2 = new Bowl(2);
}
Cupboard.java:
public class Cupboard {
Bowl bowl3 = new Bowl(3);
static Bowl bowl4 = new Bowl(4);
Cupboard() {
System.out.println("Cupboard()");
bowl4.f1(2);
}
void f3(int marker) {
System.out.println("f3 (" + marker + ")");
}
static Bowl bowl5 = new Bowl(5);
}
Test.java:
public class Test {
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);
}
static Table table = new Table();
static Cupboard cupboard = new Cupboard();
}
输出结果:
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)
分析:初始化的顺序是:先静态对象,而后是“非静态”对象。
要执行main(),首先初始化静态域table和cupboard,这导致他们对应的类也被加载,并且由于它们都包含静态的Bowl对象,因此Bowl随后也被加载。这样,在这个特殊的程序中的所有的类在main()开始之前就都被加载了。
个人理解: 首先从main()函数开始,对静态域Table进行初始化,加载Table类,Table类中包含静态的Bowl对象,接着加载Bowl类,加载Bowl类构造器创建bowl1对象,输出Bowl(1),加载Bowl类构造器创建bowl2对象,输出Bowl(2);同理创建cupboard对象。
需要注意的是,bowl3是非静态域,每次创建Cupboard对象都会创建一个Bowl对象。
