Difference between static block and assigning static in class?

Is there any difference between following two initializations of static variables:

class Class1 {    
    private static Var var;

    static {
        var = getSingletonVar();
    }  
}

class Class2 {
    private static var = getSingletonVar;
}

Are these two different ways of initializing a static variable functionally the same?


Yes, its functionally the same.

From Java doc

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.

The result will be same.

In both the cases static variable will get initialized with class loading.

static methods and static class blocks are two different things. static methods need to be called where as static class block automatically gets executed with class loading.


First Thing you haven't declared static methods here. probably if you want know order of execution

1) constructors

Invoked when you create an instance, totally independent of when #2 happens, or even if it ever happens at all

2)static methods

Invoked when you invoke them, totally independent of when #1 happens, or even if it ever happens at all

3)static blocks

Invoked when the class is initialized, which happens before #1 or #2 can happen.

链接地址: http://www.djcxy.com/p/79696.html

上一篇: ASP.NET MVC现在是“开源”。 这是一件好事吗?

下一篇: 在课堂上静态块和分配静态之间的区别?