ITEM 4: Enforce noninstantiability with a private constructors - saurabhojha/Effective-java GitHub Wiki

Utility classes:

A class that solely consists of static functions and are not meant to be instantiated is called utility/helper class. Unlike the concept of oops that correlates both data and behaviour, utility classes are meant only for behaviours. All the data are passed to the methods in the utility classes. Thus, they do not exactly fall under the oops paradigm of programming. These classes are misused sometimes, since they are easier to code. Utility classes however have several uses:

  1. Java.lang.Math in java, is a utility class that handles mathematical functions for primitives.
  2. Java.util.Collections groups together static methods for objects that implement some interface.

Since all the methods are static, it makes no sense to instantiate such classes. Hence it becomes important to enforce noninstantiability for such classes.

  1. Declaring classes abstract is not equivalent to enforcing noninstantiability because such classes can be inherited and thus, can be instantiated in some form.

Making constructor private: When a class does not have a constructor defined by the user, a default constructor is automatically generated by the compiler and is indistinguishable from a user defined default constructor. This constructor can thus be used to instantiate a utility class. By making the constructor of a utility class private, we can enforce noninstantiability.

We have to make sure that these conditions are met to make a utility class non instantiable.

  1. Make the utility class private, so that it becomes inaccessible without a helper method from the same class.
  2. Ensure the constructor cannot be accessed by modifying the behaviour of the constructor at runtime. (Make your constructor is reflection proof). This can be done by throwing a runtime error from the constructor in case it is invoked.
  3. Ensure that the static methods do not invoke the constructor. (This can also be ensured by the second condition).

Thus a noninstantiable utility class would look something like this:

public class UtilityClass {

      // Supress default constructor for noninstantiability.
      private UtilityClass() {
              throw  new AssertionError("Private constructor invoked!!");
      }

} 

Utility class may sound appealing as they are easier to code. However they worsen the testability of a code and hence must be used with good thought. Read to this article find more about it.