For example:
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
// Private constructor suppresses
// default public constructor
private Singleton() {};
public static Singleton getInstance() {
return INSTANCE;
}
}
Why can't I set the INSTANCE public, and access it by Singleton.INSTANCE? What will it cause?
You technically can and in this code, it will have no effect - it will behave the same.
The reasons we use getters in general are:
new Singleton() every time instead of accessing the static variable). Not so easy if that hundred places access the variable directly.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