Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I get the singleton instance by accessing it directly? [duplicate]

Tags:

java

singleton

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?

like image 506
Paul Zhang Avatar asked Nov 15 '25 20:11

Paul Zhang


1 Answers

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:

  • A good habit - people will be surprised to see you access a variable directly
  • Flexibility - if you have a hundred places around the code calling the getter, it's easy enough to change the method behavior (like returning new Singleton() every time instead of accessing the static variable). Not so easy if that hundred places access the variable directly.
like image 148
Antonín Karásek Avatar answered Nov 17 '25 08:11

Antonín Karásek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!