Java: When is a static initialization block useful?

前端 未结 13 1697
时光说笑
时光说笑 2020-11-30 16:49

What\'s the difference between initialization within a static block:

public class staticTest {

    sta         


        
13条回答
  •  余生分开走
    2020-11-30 17:00

    A static initialization blocks allows more complex initialization, for example using conditionals:

    static double a;
    static {
        if (SomeCondition) {
          a = 0;
        } else {
          a = 1;
        }
    }
    

    Or when more than just construction is required: when using a builder to create your instance, exception handling or work other than creating static fields is necessary.

    A static initialization block also runs after the inline static initializers, so the following is valid:

    static double a;
    static double b = 1;
    
    static {
        a = b * 4; // Evaluates to 4
    }
    

提交回复
热议问题