Java - Prevent Instantiation of Class (Enforce Noninstantiability)

Sometimes you may need to create a class that contains only collection of static values or static methods. Such classes should not be instantiable. However, users may misuse it by calling the constructor. Even if you don't provide any constructor, the compiler will provide a default public constructor with no parameter. How to enforce noninstantiability of a class?

It's very easy to prevent instantiation. You only need to provide a private constructor. Below is an example of utility class with private constructor.

MyUtils.java.

  public class MyUtils {
      private MyUtils() {}

      public static String getSomething() {
          MyUtils myUtils = new MyUtils(); // Possible to call the constructor within class
          return "ABCDE";
      }
  }

If you try invoke the constructor from another class MyUtils myUtils = new MyUtils();, you'll get error: MyUtils() has private access in MyUtils at the compile time. That's expected because the constructor has private access. However, calling the constructor inside the utility class is still possible. To prevent instantiation withtin the class, modify the constructor to throw error if it's invoked.

MyUtils.java

  public class MyUtils {
      private MyUtils() {
          throw new AssertionError();
      }

      public static String getSomething() {
          return "ABCDE";
      }
  }