// 先上主代码

public class Debug {
    // ---------------------block
    static { System.out.println("static block in debug"); }

    { System.out.println("Block in Debug"); }
    // ---------------------block

    public Debug() {
        System.out.println("Debug");
    }

    class Inner {
        public Inner() {
            System.out.println("Inner");
        }

        // block
        { System.out.println("Block in Inner"); }
        // block
    }

    static class StaticInner {
        public StaticInner() {
            System.out.println("StaticInner");
        }

        // block
        static { System.out.println("static block in StaticInner"); }

        { System.out.println("Block in StaticInner"); }
        // block
    }

    ////////////////////////////////////////////

    public static void main(String[] args) {

    }

}

  • 忽视各种内部类
public static void main(String[] args) {
    Debug debug = new Debug();
}

结果

static block in Debug
Block in Debug
Debug

结论: 在一个类中, 类加载是先加载静态代码块,然后加载代码块,最后加载构造方法。内部类、静态内部类均未被加载。


  • 内部类
public void test() {
new Inner();
}

////////////////////////////////////////////

public static void main(String[] args) {
new Debug().test();
}

结果

static block in Debug
Block in Debug
Debug
Block in Inner
Inner

结论: 内部类中代码块优先于构造方法。


  • 静态内部类
public static void main(String[] args) {
    new StaticInner();
}

结果

static block in Debug
static block in StaticInner
Block in StaticInner
StaticInner

结论: 外部类的静态代码块,静态内部类的静态代码块,静态内部类的代码块,静态内部类的构造方法。


  • 外部类和静态内部类

A

public static void main(String[] args) {
new Debug();
new Debug.StaticInner();
}

结果

static block in Debug
Block in Debug
Debug
static block in StaticInner
Block in StaticInner
StaticInner

结论 : 先创建外部类 Debug 对象,创建过程中无关静态内部类。然后创建静态内部类

B

public static void main(String[] args) {
new Debug.StaticInner();
new Debug();
}

结果

static block in Debug
static block in StaticInner
Block in StaticInner
StaticInner
Block in Debug
Debug

结论: 外部类的静态代码块依旧最先加载,然后加载静态内部类,最后加载外部类的代码块及其构造方法


  • 全局作用域变量

A

StaticInner staticInner = new StaticInner();

public static void main(String[] args) {
System.out.println(new Debug().staticInner);
}

结果

static block in Debug
Block in Debug
static block in StaticInner
Block in StaticInner
StaticInner
Debug
Debug$StaticInner@4554617c

结论: (静态)代码块比构造方法更先加载, 作用域更高一层的变量的构造方法更先加载

B

static StaticInner staticInner = new StaticInner();

public static void main(String[] args) {

}

结果

static block in Debug
static block in StaticInner
Block in StaticInner
StaticInner

结论: 略

C

Inner inner = new Inner();

public static void main(String[] args) {
System.out.println(new Debug().inner);
}

结果

static block in Debug
Block in Debug
Block in Inner
Inner
Debug
Debug$Inner@4554617c

结论: 同 A


c_c

c_c

正义永不缺席!!!!

0 条评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注