Why use static blocks over initializing instance variables directly?

前端 未结 5 2041
情歌与酒
情歌与酒 2021-01-04 20:15

Why would I use a static block:

static {
   B = 10;
}

over:

Integer B = 10;

What is the advantages/disadv

5条回答
  •  失恋的感觉
    2021-01-04 20:34

    Actually, if you have

    private static Integer B = 10;
    

    The compiler will translate to, basically:

    private static Integer B;
    static {
        B = 10;
    }
    

    The thing with static blocks is that you can use the whole language and not just expressions to do initialisation. Imagine you need an array with a bunch of multiples of 7. You could do:

    private static Integer[] array;
    static {
        array = new Integer[1000];
        for (int i = 0; i < 1000; i++) {
            array[i] = 7 * i;
        }
    }
    

    Anyway, you could also do it this way:

    private static Integer[] array = initArray();
    private static Integer[] initArray() {
        Integer[] result = new Integer[1000];
        for (int i = 0; i < 1000; i++) {
            result[i] = 7 * i;
        }
        return result;
    }
    

提交回复
热议问题