Enforce noninstantiability with a private constructor

Occasionally you’ll want to write a class that is just grouping of a static methods and static fields. Such classes have acquired a bad reputation because some people abuse them to avoid thinking in terms of objects, but they do have valid uses. They can be used to group related methods on primitive values or arrays, in the manner of java.lang.Math or java.util.Arrays. They can also be used to group static methods, including factory methods for objects that implement a particular interface, in the manner of java.util.Collections.

Such utility classes where not designed to be instantiated: an instance would be nonsensical. In the absence of explicit constructor, the compiler provides a public, parameterless default constructor. Attempting to enforce noninstantiability by making a class abstract does not work. The class can be subclassed and the subclass instantiated. Furthermore, it misleads the user into thinking that class was designed for inheritance.

A class can be made non instantiable by including a private constructor:

// Non instantiable utility class
public class UtilityClass {
  // Suppress default constructor for noninstatiability
  private UtilityClass() {
    throw new AssertionError();
  }
  ...
}

Because the explicit constructor is private, it is inaccessible outside the class. The AssertionError() isn’t strictly required, but it provides insurance in case the constructor is accidentally invoked from within class.

Lasă un răspuns

Adresa ta de email nu va fi publicată. Câmpurile obligatorii sunt marcate cu *

Acest sit folosește Akismet pentru a reduce spamul. Află cum sunt procesate datele comentariilor tale.