Static block in Java not executed

前端 未结 5 1429
长情又很酷
长情又很酷 2020-11-28 03:32
class Test {
    public static void main(String arg[]) {    
        System.out.println("**MAIN METHOD");
        System.out.println(Mno.VAL); // SOP(9090)         


        
5条回答
  •  独厮守ぢ
    2020-11-28 04:05

    1. A static final int field is a compile-time constant and its value is hardcoded into the destination class without a reference to its origin;
    2. therefore your main class does not trigger the loading of the class containing the field;
    3. therefore the static initializer in that class is not executed.

    In specific detail, the compiled bytecode corresponds to this:

    public static void main(String arg[]){    
        System.out.println("**MAIN METHOD");
        System.out.println(9090)
        System.out.println(9190)
    }
    

    As soon as you remove final, it is no longer a compile-time constant and the special behavior described above does not apply. The Mno class is loaded as you expect and its static initializer executes.

提交回复
热议问题