Sometimes we want to write a class that is just a group of static methods and fields. They can be used --
- group related methods on primitive values and arrays (e.g. java.lang.Math or java.util.Arrays)
- group static methods, including factories, for objects that implement same interfaces (e.g. java.util.Collections)
- group methods on final class, since we cannot put them in subclass.
Theses classes are not designed to be instantiated, so we can add a private constructor for them.
// Nonintantiable Utility class
public class UtilityClass {
// Suppress default constructor for noninstantiability
private UtilityClass() {
throw new AssertionError();
}
}
As a side effect, the idiom also prevents the class from being subclassed. Because all constructor must invoke its superclass constructor.