Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a Java singleton use static variables? [duplicate]

Tags:

java

singleton

Should a singleton in Java use static variables or member variables? Are there any advantages to either?

like image 641
Andreas Avatar asked Sep 05 '13 10:09

Andreas


People also ask

Can a singleton class have static variables?

Singleton implementation can either have static members or instance members. Static classes can contain static members only. It can implement any other interface or base class is required. It cannot implement the interface or any other base class.

Does a singleton need to be static?

The Singleton class does not require you to use the static keyword everywhere. Static class objects cannot be passed as parameters to other methods whereas we can pass instances of a singleton as a parameter to another method.

What is one of the most common mistakes you can make when implementing a singleton?

A common mistake with that implementation is to neglect synchronization, which can lead to multiple instances of the singleton class.

Why getInstance is static in singleton?

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.


1 Answers

You should use member variables. A singleton is an object (i.e. an instance of a class) and so should be modelled as such; even if you only ever intend to create one of them.

Statics should be used for class level variables.

like image 130
Bathsheba Avatar answered Sep 21 '22 23:09

Bathsheba