Static Initialization Blocks

前端 未结 14 1261
暗喜
暗喜 2020-11-22 01:56

As far as I understood the \"static initialization block\" is used to set values of static field if it cannot be done in one line.

But I do not understand why we ne

14条回答
  •  温柔的废话
    2020-11-22 02:22

    Here's an example:

      private static final HashMap MAP = new HashMap();
      static {
        MAP.put("banana", "honey");
        MAP.put("peanut butter", "jelly");
        MAP.put("rice", "beans");
      }
    

    The code in the "static" section(s) will be executed at class load time, before any instances of the class are constructed (and before any static methods are called from elsewhere). That way you can make sure that the class resources are all ready to use.

    It's also possible to have non-static initializer blocks. Those act like extensions to the set of constructor methods defined for the class. They look just like static initializer blocks, except the keyword "static" is left off.

提交回复
热议问题