在类的内部,变量定义的顺序决定了初始化的顺序.即使变量定义散布于方法定义之间,它们仍会在任何方法调用之前得到初始化.
无论创建多少个对象,静态数据只占用一份储存区域.静态变量初始化只有在必要时才会执行,比如有类Table,如果不创建Table对象也不引用Table的静态方法,那么类Table的静态变量永远也不会被创建.只有在第一个对象被创建或者第一次引用时,他们才会被初始化.
变量的初始化顺序 静态变量(静态块)->非静态变量(非静态块)->构造器
package sinhen.base;
public class House {
static Table tb1 = new Table(1);
static Table tb2 = new Table(2);
public static void main(String[] args) {
Table.addCup(99);
}
}
class Table{
static Cup cup1 = new Cup(1);
static Cup cup2;
static {
cup2 = new Cup(2);
}
static Cup cup3 = new Cup(3);
Cup cup4 = new Cup(4);
Cup cup5;
{
cup5 = new Cup(5);
}
Cup cup6 = new Cup(6);
private int idx;
public Table(int idx) {
this.idx = idx;
System.out.println("table " + idx);
}
public static void addCup(int cupIdx) {
System.out.println("addCup"+cupIdx);
}
}
class Cup{
public Cup(int idx) {
System.out.println("cup " + idx);
}
}
执行结果
cup 1
cup 2
cup 3
cup 4
cup 5
cup 6
table 1
cup 4
cup 5
cup 6
table 2