The sole purpose is to enforce noninstantiability. Since it is private
, the AssertionError
is mainly for reflection and for the class itself because private constructors can be called from the class itself. And as a side effect, this idiom also prevents the class from being subclassed.
Quoting from Effective Java 2nd Edition Item 4:
// Noninstantiable utility class
public class UtilityClass {
// Suppress default constructor for noninstantiability
private UtilityClass() {
throw new AssertionError();
}
... // Remainder omitted
}
Because the explicit constructor is private, it is inaccessible outside of the
class. The AssertionError isn’t strictly required, but it provides insurance in
case the constructor is accidentally invoked from within the class. It guarantees
that the class will never be instantiated under any circumstances. This idiom is
mildly counterintuitive, as the constructor is provided expressly so that it cannot
be invoked. It is therefore wise to include a comment, as shown above.
As a side effect, this idiom also prevents the class from being subclassed. All
constructors must invoke a superclass constructor, explicitly or implicitly, and a
subclass would have no accessible superclass constructor to invoke.
Also you might find this Question useful:
What is the preferred Throwable to use in a private utility class constructor?