Why should I use a static initialization block in java?

Why should I use a static initialization block when I can initialize static members through a constructor?

+5
source share
3 answers

First, you may not have instances of your class. Or you might want the static elements to be iniailized before you have any instances of the class.

Secondly, initializing static elements from constructors works more:

  • you need to make sure that every constructor does this:
  • you need to maintain a flag to track the initialization of static elements;
  • you need to think about synchronization to prevent race conditions;
  • , , .

, ( "", ).

+3

, . , . .

+1

, :

static Set<String> digits = new HashSet<String>();
static {
    Collections.add(digits, "unu", "du", "tri", "kvar", "kvin");
    digits.add("ses");
    digits.add("sep");
    digits.add("ok");
}

:

static Set<String> digits = new HashSet<String>() {{
    Collections.add(this, "unu", "du", "tri", "kvar", "kvin");
    add("ses");
    add("sep");
    add("ok");
}};
  • , ; .
  • - -.
0

All Articles