开发者

Java basics: a static function without a name, or return type

public class Main {
    public static final Logger LOGGER = Logger.getLogger(Main.class.getName());

    static {
        try {
             LOGGER.addHandler(new FileHandler("errors.log",true));
        }
        catch(IOException ex) {
             LOGGER.log(Level.WARNING,ex.toString(),ex);
        }
    }
...

I'm wondering what is this nameless static function about.

I never saw anything like this in java (which I'm currently learning).

What is it for ?

When is it typ开发者_如何学JAVAically used ?

When is this gonna be executed in the program ?


That is called a static block and will only be executed once during initialization. Also, if there are more than one static initialization blocks, the run time guarantees that they will be called in the order they appear in the source code.

Here is a pretty good explanation with some example code a. https://www.geeksforgeeks.org/g-fact-79/


It is executed once when the class is loaded. In this specific case it sets up a logger for the application.


You can only work with static member variables with a static block. And notify that even you call the constructor multiple times, static block will run only once on JVM.

Why we need static block ? Because we cannot initialize our static final member variables within the constructor, it does not make any sense.

So, you can init your static variables with Constructor, because they are created per instance. And you should init your static final variables within a static block. Initialization of non-final static member variables are either can be written inside the static block or not, that's a choice. You may want to init the same value on each instance at creation, then you assign the static variable within the Constructor to reset the static variable. If you just want to set the static variable once, then even if it is not a final member variable, then you must write init statement inside the static block.

Here is a simple demo;

A - Sample Model Class With A Static Initialization Block

public class SampleModel {

    private int index;                          // Will be init within the constructor
    private static final int MAX_VALUE;         // Will be init within static block
    private static String messageOfTheDay;      // Will be init within static block

    // Argument Constructor
    public SampleModel(int index) { 
        this.index = index;
        System.out.println("Constructor called");
    }

    // static block, will be run only once!
    static {
        System.out.println("WARNING: Static Block called !");

        MAX_VALUE = 69;
        messageOfTheDay = "I'm here";
    }

    public String getMessageOfTheDay() {
        return messageOfTheDay;
    }

    public int getMaxValue() {
        return MAX_VALUE;
    }

    public int getIndex() {
        return index;
    }

}

B - Demo Code

public class StaticBlockDemo {

    public static void main(String[] args) {
        SampleModel obj1 = new SampleModel(1);
        SampleModel obj2 = new SampleModel(2);
        SampleModel obj3 = new SampleModel(3);

        System.out.println();
        System.out.println( "obj1 : index    : " + obj1.getIndex() );
        System.out.println( "obj1 : Max Value: " + obj1.getMaxValue() );
        System.out.println( "obj1 : Max MOTD : " + obj1.getMessageOfTheDay() + "\n");

        System.out.println( "obj2 : index    : " + obj2.getIndex() );
        System.out.println( "obj2 : Max Value: " + obj2.getMaxValue() );
        System.out.println( "obj2 : Max MOTD : " + obj2.getMessageOfTheDay() + "\n");

        System.out.println( "obj3 : index    : " + obj3.getIndex() );
        System.out.println( "obj3 : Max Value: " + obj3.getMaxValue() );
        System.out.println( "obj3 : Max MOTD : " + obj3.getMessageOfTheDay() + "\n");

    }

}

C - Output

WARNING: Static Block called !
Constructor called
Constructor called
Constructor called

obj1 : index    : 1
obj1 : Max Value: 69
obj1 : Max MOTD : I'm here

obj2 : index    : 2
obj2 : Max Value: 69
obj2 : Max MOTD : I'm here

obj3 : index    : 3
obj3 : Max Value: 69
obj3 : Max MOTD : I'm here

Notify that on the output, constructor is called 3 times however static block is only called once.


That's a Static Initialization Block which is run once when the class is loaded. It can be used to initialize static member variables.


It's a static initializer, which will be executed during class initialization. As you can see, it allows you to run complex logic during that stage, including exception handling.


It a initialization block and called at the time of class loading.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜