Use and flow of Static statements in Singleton Program

后端 未结 6 623
面向向阳花
面向向阳花 2021-01-14 13:29

I know there are lot of questions on Singleton pattern. But here what I would like to know about the output which might also cover how \"static\" works in Java.



        
6条回答
  •  耶瑟儿~
    2021-01-14 14:03

    You should rather declare it as final

    private static final Singleton currentSingleton = new Singleton();
    
    1. final class variables and fields of interfaces whose values are compile-time constants are initialized

    Answer to your both questions From JLS#8.3.2. Initialization of Fields

    If the declarator is for a class variable (that is, a static field), then the variable initializer is evaluated and the assignment performed exactly once, when the class is initialized (§12.4.2).

提交回复
热议问题