I have encountered the following code:
public final class MainActivity extends ActivityBase
{
static
{
Logger.create();
}
...
}
what does static
area like this means?
What's the advantage using this syntax?
I have encountered the following code:
public final class MainActivity extends ActivityBase
{
static
{
Logger.create();
}
...
}
what does static
area like this means?
What's the advantage using this syntax?
Official Documentation
A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:
static {
// whatever code is needed for initialization goes here }
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
There is an alternative to static blocks — you can write a private
static method:
class Whatever {
public static varType myVar = initializeClassVariable();
private static varType initializeClassVariable() {
// initialization code goes here
}
}
The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.
Whenever the class is loaded (imported), the static
block will execute. It's usually used to initialize static variables and whatnot.
It is a static initializer. It allows one to initialize static
variables (even static final
) by using a set of statements instead of just an expression.
In this case, it performs an activity whenever the class is first referenced, even without creating an instance of the class.