Android:I do not understand: static { foo();}

130 views Asked by At

Sometimes I see something like it, in a class in Android:

static
{
    foo();
}
  • What does this do?

  • Why?

3

There are 3 answers

0
Blackbelt On BEST ANSWER

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 called foo(). 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 time

static ArrayList<String> test = new ArrayList<String>() {{
    add("A");
    add("B");
    add("C");
}};

but as you can see it is not easy to read. If you use a static block instead

  static ArrayList<String> test;
  static {
        test = new ArrayList<>();
        test.add("a");
        test.add("b");
        test.add("c");
    } 

or as in your question have

static ArrayList<String> test;
static {
  foo();
}

private static void foo() {
    test = new ArrayList<>();
    test.add("a");
    test.add("b");
    test.add("c");
}
0
Jimeux On

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.
0
user3476093 On

A static class member means it can be called without having an instance of a variable.

e.g.

class my_class
{
    static void my_static_function()
    { 
    // whatever
    }
}

You can call it in both ways:

my_class::my_static_function();

my_class m;
m.my_static_function();