jvm的学习笔记:二、类的初始化,代码实战(1)

  • 对于静态字段来说,直接定义该字段的类才会被初始化
    • System.out.println(MyChild1.str);
    • 输出:
    • myParent1 static block
    • hello myParent1
    • 依据:直接使用MyChild1.str,MyChild1的static没有被初始化
  • 当一个类被初始化时,要求其全部父类被初始化完毕。
    • System.out.println(MyChild1.str2);
    • 输出:
    • myParent1 static block
    • MyChild1 static block
    • hello MyChild1
    • 依据:调用MyChild1.str2时,MyParent1类被初始化了。

public class MyTest1{

    public static void main(String[] args) {
        System.out.println(MyChild1.str);
        System.out.println(MyChild1.str2);
    }

}

class MyParent1{

    public static String str = "hello myParent1";

    //静态块,初始化的时候被调用
    static {
        System.out.println("myParent1 static block");
    }

}

class MyChild1 extends MyParent1{

    public static String str2 = "hello MyChild1";


    static {
        System.out.println("MyChild1 static block");
    }
}

猜你喜欢

转载自www.cnblogs.com/boychen/p/11674729.html