Static Initialization Blocks

前端 未结 14 1286
暗喜
暗喜 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:31

    You can execute bits of code once for a class before an object is constructed in the static blocks.

    E.g.

    class A {
      static int var1 = 6;
      static int var2 = 9;
      static int var3;
      static long var4;
    
      static Date date1;
      static Date date2;
    
      static {
        date1 = new Date();
    
        for(int cnt = 0; cnt < var2; cnt++){
          var3 += var1;
        }
    
        System.out.println("End first static init: " + new Date());
      }
    }
    

提交回复
热议问题