Singleton's impetuous creation

I have singleton

public class Singleton
{
     private static Singleton instance = new Singleton();

     private Singleton()
     {
         System.out.println("Instance created.");
     }

     public static Singleton getInstance()
     {
         return instance;
     }
}

I can run this code, but no instance is created unless getInstance()called. This is strange, since mine println()in the constructor should execute, since I am using impatient instance creation.

Can someone explain?

+4
source share
2 answers
Instance

will not be created until the class is loaded for the first time, if you need an initiative without initiation without calling a method getInstance(), you can call

Class.forName(Singleton.class.getName());

upon initialization

, , , ,

+5

- , .

, , , getInstance(), , , .

+2

Source: https://habr.com/ru/post/1540987/


All Articles