Use and flow of Static statements in Singleton Program

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

    The new Singleton() statement is the first to be executed because the currentSingleton static field must be initialized; this means that memory for the Singleton object being created is allocated and its constructor is executed prior to assign the resulting object to the field variable. This is the reason of the System.out.println("Singleton private constructor..."); line being executed before the assignment. Moreover static field initialization occur as soon as the class is referenced and calling the main function of the Singleton class means refer it and this is the reason the initialization is executed before the main method.

提交回复
热议问题