Static Initialization Blocks

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

    If they weren't in a static initialization block, where would they be? How would you declare a variable which was only meant to be local for the purposes of initialization, and distinguish it from a field? For example, how would you want to write:

    public class Foo {
        private static final int widgets;
    
        static {
            int first = Widgets.getFirstCount();
            int second = Widgets.getSecondCount();
            // Imagine more complex logic here which really used first/second
            widgets = first + second;
        }
    }
    

    If first and second weren't in a block, they'd look like fields. If they were in a block without static in front of it, that would count as an instance initialization block instead of a static initialization block, so it would be executed once per constructed instance rather than once in total.

    Now in this particular case, you could use a static method instead:

    public class Foo {
        private static final int widgets = getWidgets();
    
        static int getWidgets() {
            int first = Widgets.getFirstCount();
            int second = Widgets.getSecondCount();
            // Imagine more complex logic here which really used first/second
            return first + second;
        }
    }
    

    ... but that doesn't work when there are multiple variables you wish to assign within the same block, or none (e.g. if you just want to log something - or maybe initialize a native library).

提交回复
热议问题