Why is the Object made static
in the Singleton pattern?
What is actual use of it?
What will happen if we don't make object static?
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!");
}
}
You usually keep the single instance of the Singleton class in a static variable of that class. This doesn't make that instance static. Only the reference to it is static.
Since you can only obtain that single instance via a static method of the class (you can't explicitly construct instances of a Singleton class via a constructor - otherwise it wouldn't be a singleton), the reference to that instance must be stored in a static variable.
Just adding/elaborating eran's answer,since getInstance method is static method, getInstance method can be called from main methods/other methods by using classname i.e. SingleObject.getInstance(); This means you will never need an object reference to call getInstance()
If it would have been instance method , you would have needed an object to call getInstance. Now there is no way to create an object of class SingleObject outside the class (since constructor is private ) & this is the real trouble.
Conclusion 1: This means we need to have a static method.
Conclusion 2: SO NEED TO HAVE A STATIC METHOD, MAKES THE PROPERTY TO BE STATIC, since instance property is not available inside static method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With