It is better to declare the instance of a Singleton as static
or as static final
?
See the following example:
static
version
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
static final
version
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return INSTANCE;
}
}
In your particular cases, there is no difference at all. And your second is already effectively final.
But
Keeping aside the fact that the below implementation is NOT thread safe, just showing the difference with respect to final.
In case of lazy initialization of your instance, you may feel the difference. Look lazy initialization.
public class Singleton {
private static Singleton INSTANCE; /error
private Singleton() {
}
public static Singleton getInstance() {
if (INSTANCE ==null) {
INSTANCE = new Singleton(); //error
}
return INSTANCE;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With