Let's follow the logic, we want one class to have only one object, the object is being created by the constructor, so I want to control when constructor is being called, the easiest way is to be me the only one that can call the constructor, so making the constructor private seems a good step. Once I have the instance then I have to give the possibility to get this instance by creating a getter.
But If I do not have the instance yet I cannot access the instance methods but only the static methods, so we can access them from the class.
public class MySingleton{
private static MySingleton instance=new MySingleton();
private MySingleton(){};
public static MySingleton getInstance(){
return instance;
}
}- Keep the constructor private
- initialize instance field with the private constructor
- create a getter to get the instance
But this implementation leads to the possibility to create more instances of MySingleton by extending the class, If I create a subclass of MySingleton for example MyMiniSingleton, then MyMiniSingleton is an instance also of MySingleton.