0

I'm trying to learn singleton design pattern.the code is as follow:

public class Model {

    private static final Model INSTANCE = new Model();

    public static void main(String[] args) {
        Model.getInstance();
    }

    private Model(){
        System.out.println("constructor");
    }

    public static Model getInstance(){

        System.out.println("I hope to be printed first!");
        return INSTANCE;
   }
}

I expect the code to print I hope to be printed first! first, and then go through class constructor. but the code output is reverse :

constructor
I hope to be printed first!

I cant understand why the class is instantiated first?

alex
  • 7,551
  • 13
  • 48
  • 80
  • 4
    Static fields are initialised as soon as the class loads. You need `INSTANCE` to be lazily initialised. – Sweeper Jan 27 '20 at 18:25
  • @Sweeper you mean the class was loaded when `main` was run,before the execution of `getInstance()` ? – alex Jan 27 '20 at 18:29
  • 1
    Maybe this helps? https://stackoverflow.com/questions/8297705/how-to-implement-thread-safe-lazy-initialization – jrook Jan 27 '20 at 18:34
  • @jrook thanks for the valuable reference. I'm not looking for a workaround now . i need to know what happens in the code – alex Jan 27 '20 at 18:39

2 Answers2

1

Static variables are initialized when class is loaded. They are initialized before any object of that class is created. Since static variables are initialized before any static method of the class executes, the output you are getting is as expected. Check https://beginnersbook.com/2013/05/static-variable/ and https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html for more details and some examples.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

Even before executing main() method JVM classloader loads class into memory. At this time it initializes all static variables and execute static initialization blocks in the order in which they appear in class (from top to bottom).

So since your INSTANCE variable is static it has to be initialized. So constructor is called to create an instance of of class Model to then assign to INSTANCE variable. Since this is the only static variable ans there are no static init blocks then main method is being executed which calls Model.getInstance().

When writing code that initializes different types of fields, of course, we have to keep an eye on the order of initialization.

In Java, the order for initialization statements is as follows:

static variables and static initializers in order

instance variables and instance initializers in order

constructors

https://www.baeldung.com/java-initialization

Community
  • 1
  • 1
Ivan
  • 8,508
  • 2
  • 19
  • 30