Possible Duplicate:
Static Initialization Blocks
While reviewing some old code, I found some rather odd syntax that I've never seen before. After doing some research, I know now that what I saw was a static{}
block which (if I understand correctly) is a block of code that is executed at initialization time.
What I don't understand is the advantage to having such a feature or when one would possibly want to use this. It seems like the static blocks simply contain regular lines of code which could belong in any regular static method, so what is the advantage to having it run automatically at initialization (other than saving a programmer a line of code to call a method)? Why is this important or useful?
As they say in the Java Tutorials:
If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.
As you said, static blocs are executed at initialization time. Say that you have a static field which can be pretty complex, for example
private static List<ThingsDownloadedByTheNet> ls;
just doing
private static List<ThingsDownloadedByTheNet> ls = new ArrayList<ThingsDownloadedByTheNet>
could not be enough, as you maybe want to set list elements too. So, you do a static block, in which you perform some initialization (in this case you connect to a server and populate list elements)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With