Why do we need to make instance variable as static?
- static => class level. All instances share the same copy.
Had it not been static, every instance created of this class would have been composed of it's own private instance. Why do we need to make instance variable as private?
- what if it is public? it's value can then be modified. The reference could be made to point to null by some malicious code. Result- creates another object on the next call to the same method. Why do we need to mark constructor with private?
- what if otherwise? instances of this class can be created by invoking the constructor. No more a singleton. Why do we need to make instance variable as private?
- this is a trick question. you just asked it few questions back. gotcha. Why do we need to mark method with static, synchronized?
- "static synchronized". Obtains a lock on the instance of class java.lang.Class that represents this singleton class at runtime, when this static synchronized method is invoked. The idea is to try & ensure that only one instance is created. For ex: imagine 2 threads trying to create a singleton and the context switches just after the 1st thread finshes the if predicate. Both threads end up creating an instance - not a true singleton.