Why use static blocks over initializing instance variables directly?

前端 未结 5 2056
情歌与酒
情歌与酒 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:40

    The static block allows you to write more complex initialization logic for the attribute, whereas the one-line initialization limits you to a single expression.

    Be aware that initialization blocks exist for both instance and static attributes, for example this one initializes an instance attribute at instantiation time:

    private int a;
    { a = 10; }
    

    Whereas this one initializes a static attribute at class loading time:

    private static int b;
    static { b = 10; }
    

    The initialization procedure is explained in detail in here, as part of the JVM specification.

提交回复
热议问题