What are initializers for static fields in Java

I have the following line from an Oracle Java tutorial. You can find it here. Running under the heading "12.4. Initializing Classes and Interfaces"

The initialization of a class consists of executing its static initializers and initializers for static fields (class variables) declared in the class.

It will be great if someone explains to me how “initializers for static fields” refer to “class variables”.

+4
source share
2 answers

" " - , static . " " , . :

public class MyClass {
    private static int num = 0; //This is a class variable being initialized when it is declared
}

- :

public class MyClass {
    private static int num;
    static {
        num = 0; //This a class variable being initialized in a static block
    }
}

, .

, " " - " ".

+5

A static member - , , . , .

:.

public class MyClass {
    // Note the static modifier here!
    private static int someVariable = 7;
}

static final , :

public class Human {
    public static final String SPECIES = "Homo sapiens";
    public static final int LEGAL_DRINKING_AGE = 21; // U.S centric code :-(
}
+3

All Articles