Why is a static field used for a singleton?

I've been reading up on singletons recently and I commonly see code like:

private static SingletonDemo instance = null;

Inside the Singleton class as a field.

I don't want particularly understand what 'static' is doing and why it's needed.

I read the Oracle site here. And they use a numOfBicycles (which is when you have multiple bicycles) example to justify using a static field, but I think I'm understanding something on why it's used when you're just instantiating 1 instance.

Jon Skeet
people
quotationmark

The point is that you need a way of accessing the single instance which has been created - it's effectively a global variable. That's precisely what a static field achieves. (At least, it's global as far as the relevant classloader is concerned, which is all that's important most of the time.)

If it were an instance variable, then you could only find a reference to the singleton object if you already had a reference to the singleton object, making it pretty pointless.

Most singleton implementations have a static getInstance method or something similar. Consider how you would implement that without the static field, and you're likely to get a better idea of why it's needed.

(As an aside, I'd recommend against using the singleton pattern in most cases. Using dependency injection in a way which ends up creating only one instance in production, but where each class isn't a singleton per se typically ends up giving you more testable and flexible code.)

people

See more on this question at Stackoverflow