变量初始化顺序

(1)变量定义的先后顺序决定初始化顺序,即使变量定义散布在方法定义之间,他们仍旧会在方法被调用之前得到初始化,构造方法也是特殊的方法
(2)执行顺序:静态块, 静态变量,非静态变量,构造方法
每次在创建对象的时候非静态变量都会被初始化
静态对象只会在类加载的时候被初始化一次
 
public class Initialization {

    static Table table = new Table();
    static Cupboard cupboard = new Cupboard();
    @Test
    public void test() {
        System.out.println("start...");
        new Cupboard();
        System.out.println("restart...");
        new Cupboard();
        table.method(1);
        cupboard.method(1);
    }
}

class Bowl {
    public Bowl(int maker) {
        System.out.println("Bowl " + maker);
    }
    public void method(int maker){
        System.out.println("Bowl method " + maker);
    }
}
class Table{
    static Bowl bowl1 = new Bowl(1);
    Table(){
        System.out.println("Table ");
        bowl2.method(2);
    }
    public void method(int maker){
        System.out.println("Table method " + maker);
    }
    static Bowl bowl2 = new Bowl(2);
}

class Cupboard{
    Bowl bowl3 = new Bowl(3);
    static Bowl bowl4 = new Bowl(4);
    Cupboard(){
        System.out.println("Cupboard ");
        bowl4.method(2);
    }
    public void method(int maker){
        System.out.println("Cupboard method " + maker);
    }
    static Bowl bowl5 = new Bowl(5);
}
 结果:
Bowl 1
Bowl 2
Table 
Bowl method 2
Bowl 4
Bowl 5
Bowl 3
Cupboard 
Bowl method 2
start...
Bowl 3
Cupboard 
Bowl method 2
restart...
Bowl 3
Cupboard 
Bowl method 2
Table method 1
Cupboard method 1

猜你喜欢

转载自xiaoxiaoxuanao.iteye.com/blog/2316497