Why should I use static initialization block when I can initialize static members through a constructor?
-
9What if you never have an instance of that class - but would like to use the static functions of it, which uses the values initialized by the static initializer block?ppeterka– ppeterka2013-03-06 11:41:20 +00:00Commented Mar 6, 2013 at 11:41
-
1and every time when c'tor is called, static values will be reset. bad!!Azodious– Azodious2013-03-06 11:42:46 +00:00Commented Mar 6, 2013 at 11:42
Add a comment
|
3 Answers
Firstly, you might never have any instances of your class. Or you might want to have the static members iniailized before you have any instances of the class.
Secondly, initializing static members from constructors is more work:
- you'll need to make sure that every constructor does this;
- you need to maintain a flag to keep track of whether static members have been initialized;
- you have to think about synchronization to prevent race conditions;
- you may have to consider performance implications of the synchronization, especially if you have many threads creating many instances of your class.
Lastly, it's usually the wrong thing to do conceptually (I say "usually" because there are legitimate uses for lazy initialization).
1 Comment
Stephen C
+1 - though if you were going to implement lazy (or non-lazy deferred) initialization, you probably wouldn't "make it happen" in a constructor.
So why:
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");
}
if the following is possible:
static Set<String> digits = new HashSet<String>() {{
Collections.add(this, "unu", "du", "tri", "kvar", "kvin");
add("ses");
add("sep");
add("ok");
}};
- It introduces a new anonymous class, a file in the jar; not so optimal.
- The second form is a geeky play thing.
3 Comments
David T.
why is introducing new anonymous classes not optimal? would it ever lead to classloading bugs? or are you just saying you don't want to bloat your jar.
Joop Eggen
@DavidT. I have no dislike for either form, but comparing both: the first has redundant occurrences of
digits and the second creates an anymous class (tiny overhead) and has a misleading syntax for non-java developers. The real danger would be when using a non-static {{ ... }} on a Serializable class: then the this of the surrounding class get's serialized too. I have encountered such a X.this being null after reloading of the object for instance.David T.
Actually, i found out one difference -> on Eclipse, if you get a crash inside your Anonymous class, Eclipse doesn't even know which project to point the line of crash to (like, say you have a bunch of threads and runnables as anonymous classes)