Why is an object static in a Singleton pattern?

Why is the object created staticin the Singleton template?
What is the actual use?
What happens if we do not become a static object?

public class SingleObject {

   //create an object of SingleObject
   private static SingleObject instance = new SingleObject();

   //make the constructor private so that this class cannot be
   //instantiated
   private SingleObject(){}

   //Get the only object available
   public static SingleObject getInstance(){
       return instance;
   }

   public void showMessage(){
       System.out.println("Hello World!");
   }
}
+4
source share
2 answers

Usually you store a single instance of the Singleton class in a static variable of that class. This does not make this instance static. Only a link to it is static.

Since you can only get this single instance through the static method of the class (you cannot explicitly construct instances of the Singleton class through the constructor, otherwise it would not be single), the reference to this instance should be stored in a static variable.

+3
0

All Articles