while implementing singleton as:
class MyConnection {
private static MyConnection connection = new MyConnection();
private MyConnection() {
}
public static MyConnection getConnection() {
return connection;
}
}
1)why we give connection as static?
Is this only due to the fact that getConnection() is static and we cannot reference non-static in static context or there is any other reason?
2) is it necessary to declare connection as final?
If it was non-static, you would need to have an instance of
MyConnectionto get hold of theconnectionreference which sort of defeats the purpose. 🙂Yes. (Since
getConnection()needs to be static,connectionneeds to be static.)No, but it’s good practice, since once initialized, it should not be changed.
But, an even better practice is to use an
enuminstead.and access it through
MyConnection.INSTANCE.Rule of thumb: If a class shall have a predefined number of instances, use an
enum. In this case the number of instances is one.