9/13/2012

Static Block in Java

A static block in Java looks like this:

class a {
    static {
    //...
    }
    public a() {
        //constructor
    }
}

take away essentials:

1. Static blocks are executed once the class is loaded (not necessarily to create a new instance).

2. Multiple static blocks are considered as one in code order.

3. Static blocks are executed before the constructor.

4. Omitting "static" will lead to that the code in these blocks are considered as "constructor block" and will be executed when the class is instantiated. The constructor block will be copied into each constructor of the class.

5. Better way:
class PrivateStaticMethodExample {
     public static varType myVar = initializeClassVariable();

    private static varType initializeClassVariable() {
        //initialization code goes here
    }
}

No comments:

Post a Comment