mardi 29 août 2023

I noticed that the `new` keyword is not used when creating the reference to the instance. Here's the code snippet:

public class SingletonExample { private static SingletonExample instance;

private SingletonExample() {
    // Private constructor
    System.out.println("SingletonExample instance created.");
}

public static SingletonExample getInstance() {
    if (instance == null) {
        instance = new SingletonExample();
    }
    return instance;
}

public void displayMessage() {
    System.out.println("Hello from SingletonExample!");
}

public static void main(String[] args) {
    // This won't work : SingletonExample instance = new SingletonExample();

    // Getting an instance of SingletonExample using getInstance() method
   SingletonExample singleton = SingletonExample.getInstance();
    singleton.displayMessage();
    
}

}

I expected that creating a new instance of a class would involve using the new keyword, but it appears that the getInstance() method handles this without it. I'm looking for an explanation of why the new keyword is omitted in this scenario and how the instance is actually created using the getInstance() method.

Can someone provide insights into how the getInstance() method works in this context and why the new keyword is not used?

Aucun commentaire:

Enregistrer un commentaire