Sometimes I see something like it, in a class in Android:
static
{
foo();
}
What does this do?
Why?
Sometimes I see something like it, in a class in Android:
static
{
foo();
}
What does this do?
Why?
It's a static initializer block, which are used for initializing static variables. These are run once for the life of a class (not each time you create an instance). For example, you may want to populate a static data structure in a way that can't be done usually.
There are also non-static initializer blocks. These are run every time an instance is created. They're often used to initialize the variables of anonymous classes. It's useful to know that these execute before the constructor.
class BlockTest {
static {
System.out.println("Static block.");
}
{
System.out.println("Non-static block.");
}
public BlockTest() {
System.out.println("Constructor.");
}
public static void main(String[] args) {
new BlockTest();
}
}
This code will output the following:
Static block.
Non-static block.
Constructor.
That's a
static
block. It is executed the first time that class is referenced on your code, and it is calling a static method calledfoo()
. You can find more about the static block here. As mentioned by @CommonsWare, you can initialize a static field in two different ways, inline a declaration timebut as you can see it is not easy to read. If you use a static block instead
or as in your question have