Good day colleagues! I have a very simple code:

public class Singleton { static Singleton st = new Singleton(); Singleton(){ System.out.println("Π˜Π½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΡ "); } public static void main(String[] args) { } } 

The class contains one field - itself. The entry point is empty, nothing is created in Maine. Nevertheless, the constructor executes, displays to the console:

Π˜Π½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΡ

Question: Why does a constructor work out and where can one read about it?

  • one
    at jls - zRrr
  • 3
    This is called static initialization. When a class is loaded, all static fields are initialized and static blocks are executed. You have a static Singleton st field that is static, so when you load a class, this field is initialized with the value of new Singleton(); . - learp

1 answer 1

Static fields / blocks are initialized when the class is first accessed, because you have an entry point to the program in Singleton , a public static void main(String[] args) method public static void main(String[] args) , then the first call occurs.

Thus, running the program through main you start loading the class. The static field is loaded first.

static Singleton st = new Singleton() .

The new operator calls the class constructor.

The order and rules of initialization are well covered in the "Java Philosophy" by Bruce Ekkel

  • To be precise, static blocks / fields are initialized when the class is first loaded - Barmaley
  • I will add: it can do this: private Singleton st = new Singleton (); + get & setSinglton (in this case, probably just get?) - Anton Sorokin
  • @Barmaley and what does "first class load" mean? If I wrote an entry point in a class, would it be the first download or something different? - Andrew Kachalin
  • Downloading means loading a class image into a JVM - usually with a ClassLoader - Barmaley
  • @Barmaley and in my example, the image of the class got into the JVM because of the presence of the main? - Andrew Kachalin