Java: When is a static initialization block useful?

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

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

public class staticTest {

    sta         


        
13条回答
  •  感情败类
    2020-11-30 17:01

    The static code block enables to initialize the fields with more than instuction, initialize fields in a different order of the declarations and also could be used for conditional intialization.

    More specifically,

    static final String ab = a+b;
    static final String a = "Hello,";
    static final String b = ", world";
    

    will not work because a and b are declared after ab.

    However I could use a static init. block to overcome this.

    static final String ab;
    static final String a;
    static final String b;
    
    static {
      b = ", world";
      a = "Hello";
      ab = a + b;
    }
    
    static final String ab;
    static final String a;
    static final String b;
    
    static {
      b = (...) ? ", world" : ", universe";
      a = "Hello";
      ab = a + b;
    }
    

提交回复
热议问题