Why use static blocks over initializing instance variables directly?

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

    Static initialization happens when the class is loaded.

    E.g. it would be a proper place to initialize member variables that could otherwise need synchronization due to access by multiple threads.

    The second case would happen if you called the constructor explicitely.

    The usage is different.
    E.g. you would prefer the second case for lazy loading of something (if you put it in static initializers it will always load and perhaps you would not want that-prefer to lazy load it)

提交回复
热议问题