Execution order of of static blocks in an Enum type w.r.t to constructor

前端 未结 3 735
栀梦
栀梦 2020-12-19 00:01

This is from Effective Java :

// Implementing a fromString method on an enum type
  private static final Map stringToEnum
      = ne         


        
3条回答
  •  失恋的感觉
    2020-12-19 00:28

    I understand your question as: why is there a guarantee that the enum constants will be initialised before the static block is run. The answer is given in the JLS, and a specific example is given in #8.9.2.1, with the following explanation:

    static initialization occurs top to bottom.

    and the enums constants are implicitly final static and are declared before the static initializer block.

    EDIT

    The behaviour is not different from a normal class. The code below prints:

    In constructor: PLUS
    PLUS == null MINUS == null
    
    In constructor: MINUS
    PLUS != null MINUS == null
    
    In static initialiser
    PLUS != null MINUS != null
    
    In constructor: after static
    PLUS != null MINUS != null
    
    public class Operation {
    
        private final static Operation PLUS = new Operation("PLUS");
        private final static Operation MINUS = new Operation("MINUS");
    
        static {
            System.out.println("In static initialiser");
            System.out.print("PLUS = " + PLUS);
            System.out.println("\tMINUS = " + MINUS);
        }
    
        public Operation(String s) {
            System.out.println("In constructor: " + s);
            System.out.print("PLUS = " + PLUS);
            System.out.println("\tMINUS = " + MINUS);
        }
    
        public static void main(String[] args) {
            Operation afterStatic = new Operation ("after static");
        }    
    }
    

提交回复
热议问题