0

From https://en.wikipedia.org/wiki/Singleton_pattern#Implementation

An implementation of the singleton pattern must:

  • ensure that only one instance of the singleton class ever exists; and
  • provide global access to that instance.

Typically, this is done by:

  • declaring all constructors of the class to be private; and
  • providing a static method that returns a reference to the instance.

The instance is usually stored as a private static variable; the instance is created when the variable is initialized, at some point before the static method is first called. The following is a sample implementation written in Java.

public final class Singleton {
    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return INSTANCE;
    }
}

Are final on class Singleton and private on Singleton() redundant with each other?

Does only either of them suffice?

Thanks.

  • No. `final` means the class can't be extended, whereas a `private` constructor means it can't be called outside of the scope of the class. – bgfvdu3w Sep 29 '17 at 01:32

1 Answers1

3

In general, the two keywords are not "redundant with each other". That is, they have different effects.

Declaring Singleton as final means that it cannot be sub-classed. Declaring its constructor as private means that it cannot be instantiated by others. The latter is generally what you need to enforce the Singleton pattern.

However, as the OP noted in the comment to first draft of my answer, declaring the constructor as private does prevent sub-classing in this instance. This is because there is no other constructor available to sub-classes. So, in this case, declaring the class as final is unnecessary. However, if there were another constructor declared as protected, then a sub-class could be created.

dave
  • 11,641
  • 5
  • 47
  • 65
  • Thanks. Doesn't making its constructor private prevent it from being subclassed , so imply `final` on the class? –  Sep 29 '17 at 01:34
  • Can a singleton class have more than one constructors? If yes, must they all be private or protected? –  Sep 29 '17 at 01:55
  • If a Singleton did have more than one constructor then yes, they must all be private or protected. Remember, the point is to control access to a single (or small set of) instance(s). A public constructor would circumvent this control. – dave Sep 29 '17 at 02:19
  • Would a Singleton have more than one constructor? It's possible. I seem to recall a Singleton with more than one instance method. Each method accepted a different type of (injected) configuration. Conceivably this Singleton would have had different constructors for the different cases. – dave Sep 29 '17 at 02:21
  • Thanks. In https://stackoverflow.com/a/16662680/3284469, why can `B` subclass `A`, when `A` only have one constructor, and the only constructor of `A` is private? Does `B`'s constructor `B()` not call `A()`? –  Sep 29 '17 at 02:44