Enforce noninstantiability with a private constructor

Sometimes we want to create a class that is non instantiable: a class of static helper methods or constants. Let’s see how to make sure that such a class is never instantiated.

Why should’t we have separate helper method classes? In general, it is not considered a good object oriented design. But the world is not always black and white… So, to design a noninstatiable classe we can use a private constructor. An exception thrown in the constructor body, prevents its construction if somebody accesses it through reflection.

Why do we need a private constructor? Because if no constructor is given for the class, the compiler create a default, parameterless one. If we do create one, even a private one, the compiler will not need to add anything more.

Sample code for a noninstantiable class:

public class Helpers {
    private Helpers() {
        throw new AssertionError();
    }
    (...)
}

This post is based on item Enforce noninstantiability with a private constructor from Joshua Bloch Effective Java Third Edition (get it on Amazon: https://www.amazon.com/Effective-Java-3rd-Joshua-Bloch/dp/0134685997)