Use and flow of Static statements in Singleton Program

后端 未结 6 588
面向向阳花
面向向阳花 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 13:52

    You cannot invoke the main method in the class until it has been properly initialized (i.e. static fields and static blocks have been evaluated). When it is initialized, an instance of your singleton is created by invoking the private constructor. Later the main method is invoked.

    The class in question has a static field to which you assing a value. Since the field is static it must be initialized before the class can be used in any context, that is, it must receive a value. In this case its value happens to be an instance of the same class. This is what triggers your private costructor during class initialization.

    If you want to delve into the process and understand it better please refer to the Java Laguage Specification. More specifically in the section12.4 Initialization of Classes and Interfaces you will find further details.

提交回复
热议问题