1、调用运行期常量,接口和类都会触发初始化:
public class MyTest1 {
public static void main(String[] args) {
System.out.println(Child.b);
System.out.println(ChildClass.b);
}
}
interface Parent {
public static String a = "Hello World";
}
interface Child extends Parent {
// public static final String b = "childinterface b";
public static final String b = UUID.randomUUID().toString();
public static final Thread thread = new Thread(){
{
System.out.println("childinterface thread invoked");
}
};
}
class ChildClass{
// public static final String b = "ChildClass b ";
public static final String b = UUID.randomUUID().toString();
public static final Thread thread = new Thread(){
{
System.out.println("childClass thread invoked");
}
};
}
运行结果如下,
childinterface thread invoked
1f078d18-96f1-4b30-9b26-eba86bcdd417
childClass thread invoked
f9ef3a83-26ed-4ce0-ae46-1a22b5264a24
2.调用编译器常量,都不会触发类或接口的初始化(因为已经放入调用类的常量池中)
public class MyTest1 {
public static void main(String[] args) {
System.out.println(Child.b);
System.out.println(ChildClass.b);
}
}
interface Parent {
public static String a = "Hello World";
}
interface Child extends Parent {
public static final String b = "childinterface b";
// public static final String b = UUID.randomUUID().toString();
public static final Thread thread = new Thread(){
{
System.out.println("childinterface thread invoked");
}
};
}
class ChildClass{
public static final String b = "ChildClass b ";
// public static final String b = UUID.randomUUID().toString();
public static final Thread thread = new Thread(){
{
System.out.println("childClass thread invoked");
}
};
}
运行结果:
childinterface b
ChildClass b