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

  • 常量在编译阶段,会存在调用这个常量的方法的所在的类的常量池当中
    • System.out.println(MyParent2.str);
    • 输出:
    • hello parent2
    • 依据:在MyTest2类调用MyParent2.str,MyParent2中的静态类没有执行。
  • 当一个常量的值并非编译区间可以确定的,其值并不会放在调用类的常量池中,并在运行的时候,会导致主动使用这个常量所在的类,所以这个类会被初始化。
    • System.out.println(MyParent2.uuid);
    • 输出:
    • myParent2 static block
    • 4c3ad416-11dd-4d05-b065-ff5df854a90a
    • 依据:在MyTest2类调用MyParent2.uuid,MyParent2中的静态类执行了。

public class MyTest2 {

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



class MyParent2{

    public static final String str = "hello parent2";

    public static final String uuid = UUID.randomUUID().toString();

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

}

猜你喜欢

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