Effective Java (Second Edition), Item 4, discusses using private constructors to enforce noninstantiability. Here\'s the code sample from the book:
public fi
No no no, with all due respect to Josh Bloch, never throw an AssertionError
unless it's from an assertion. If you want an AssertionError here, throw it with assert(false)
. Then someone reading the code can find it later.
Even better, define your own exception, say CantInstantiateUtilityClass
. then you'll have code that says
try {
// some stuff
} catch (CantInstantiateUtilityClass e) {
// react
}
so that the reader of the catcher knows what happened.
Let me just note that the standard still defines AssertionError
as the result of a failed assertion, not as what some beginner thinks ought to be thrown in place of a well-defined informative exception. Sadly, good exception discipline is perhaps the least encouraged skill in Java programming.
UnsupportedOperationException sounds like the best fit, though a checked exception would be even better, since it might warn someone erroneously instantiating the class at compile time.