关于“调用类中的static final常量时并不会触发该类的初始化,但是调用接口中的static final常量时便会触发该接口的初始化 ”的否定

余生长醉 提交于 2019-11-26 01:56:06
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 

 

 

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!