Static Initialization Blocks

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

    You first need to understand that your application classes themselves are instantiated to java.class.Class objects during runtime. This is when your static blocks are ran. So you can actually do this:

    public class Main {
    
        private static int myInt;
    
        static {
            myInt = 1;
            System.out.println("myInt is 1");
        }
    
        //  needed only to run this class
        public static void main(String[] args) {
        }
    
    }
    

    and it would print "myInt is 1" to console. Note that I haven't instantiated any class.

提交回复
热议问题