Will Lin Will Lin - 2 years ago 112
Java Question

Java - Only one instance of class: use static methods instead?

If I know that a particular class is only going to be instantiated ONLY once in my program, would it be better to use static methods and variables instead for that particular class? If not, what would be the benefits of using instance methods and variables over static ones if there will only be one instance of that class?

Answer Source

Singleton implementation

public class A {
  private static A INSTANCE;
  // Do not allow to initiate outside
  private A() {
  // This makes sure that you get only one instance
  public static A getInstance() {
    if (INSTANCE == null) {
      INSTANCE = new A();
    return INSTANCE;
  //.... other methods

A = A.getInstance();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download