This is my singleton class for obtaining the database connection.
I have a question here: why it compulsory to have a private constructor inside a singleton class (a
For singletons and utilty classes you can use an enum
which is a final class and implicitly defines a private constructor.
enum Singleton {
INSTANCE
}
or
enum Utility {;
}
In your example above you have a utility class because you have no instance fields, methods and don't create an instance.
If there no such a private constructor, Java will provide a default public one for you. Then you are able to call this constructor multiple times to create several instances. Then it is not a singleton class any more.
If you don't need lazy initiation:
public class Singleton {
private static final Singleton instance = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() { }
public static Singleton getInstance() {
return instance;
}
}
is the best way, because is thread safe.
For the singleton pattern you use an private constructor to ensure that no other instances can be created, otherwise it wouldn't be a singleton.