Item4 Enforce noninstantiability with a private constructor

Sometimes we want to write a class that is just a group of static methods and fields. They can be used --

  1. group related methods on primitive values and arrays (e.g. java.lang.Math or java.util.Arrays)
  2. group static methods, including factories, for objects that implement same interfaces (e.g. java.util.Collections)
  3. group methods on final class, since we cannot put them in subclass.

Theses classes are not designed to be instantiated, so we can add a private constructor for them.

// Nonintantiable Utility class
public class UtilityClass {
  // Suppress default constructor for noninstantiability
  private UtilityClass() {
    throw new AssertionError();
  }
}

As a side effect, the idiom also prevents the class from being subclassed. Because all constructor must invoke its superclass constructor.

你可能感兴趣的:(Item4 Enforce noninstantiability with a private constructor)