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 (as throughout my entire application I am calling this class only once) and as one instance of a class can be achieved using the static method?
Can this private constructor can be avoided, or is it mantadatory?
public class ConnPoolFactory {
private static DataSource dataSource;
private static Connection connection;
private ConnPoolFactory() {
System.out.println(" ConnPoolFactory cons is called ");
}
public static synchronized Connection getConnection() throws SQLException {
try {
if (connection == null) {
Context initContext = new InitialContext();
Context envContext = (Context) initContext
.lookup("java:/comp/env");
dataSource = (DataSource) envContext.lookup("jdbc/Naresh");
connection = dataSource.getConnection();
} else {
return connection;
}
} catch (NamingException e) {
e.printStackTrace();
}
return connection;
}
}
Otherwise everyone can create an instance of your class, so it's not a singleton any more. For a singleton by definition there can exist only one 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.
Singleton def:
If you want to satisfy above statement then we should give constructor as a private. Actually through singleton we are getting ref not object that's why it is not mandatory then we can create object in other classes but we can't access reference (Constructor as public).
Ex:
Other class:
Output:
For singletons and utilty classes you can use an
enum
which is a final class and implicitly defines a private constructor.or
In your example above you have a utility class because you have no instance fields, methods and don't create an instance.