Singletons that aren't actually singletons become problems instead. To make sure a singleton isn't instantiable, make sure all constructors are ``++private++``. If the singleton doesn't have any constructors then add a ``++private++`` no-args constructor to override the default constructor.


This rule raises an issue when a class that holds a ``++public static final++`` instance of itself has non-``++private++`` constructors or no constructor.


== Noncompliant Code Example

----
public class Highlander implements Immortal {  // Noncompliant; no constructor; default, public constructor generated
  public static final Highlander INSTANCE = new Highlander();

  public void eliminateRival(Immortal immortal) {
    // ...
  }
}

public class Kurgan implements Immortal {
  public static final Kurgan INSTANCE = new Kurgan();

  Kurgan() {  // Noncompliant; should be private
  }

  public void eliminateRival(Immortal immortal) {
    // ...
  }
}
----


== Compliant Solution

----
public class Highlander implements Immortal {
  public static final Highlander INSTANCE = new Highlander;

  private Highlander() {
  }

  public void eliminateRival(Immortal immortal) {
    // ...
  }
}

public class Kurgan implements Immortal {
  public static final Kurgan INSTANCE = new Kurgan;

  private Kurgan() {
  }

  public void eliminateRival(Immortal immortal) {
    // ...
  }
}
----


== See

* https://wiki.sei.cmu.edu/confluence/x/_zZGBQ[CERT MSC07-J.] - Prevent multiple instantiations of singleton objects


ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)

include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]
