Utilities: a private constructor with only static members documents a utility class

A class made entirely of static methods, like a math helper, should declare a private constructor that throws if reflection ever calls it, signalling to both the compiler and readers that the class is never meant to be instantiated.

Code
final class MathUtils {
    private MathUtils() {
        throw new AssertionError("MathUtils cannot be instantiated");
    }
    static int square(int n) {
        return n * n;
    }
}
System.out.println("square(6): " + MathUtils.square(6));
try {
    java.lang.reflect.Constructor<MathUtils> ctor = MathUtils.class.getDeclaredConstructor();
    ctor.setAccessible(true);
    ctor.newInstance();
} catch (java.lang.reflect.InvocationTargetException e) {
    System.out.println("Blocked: " + e.getCause().getClass().getSimpleName() + ": " + e.getCause().getMessage());
} catch (ReflectiveOperationException e) {
    System.out.println("Reflection error: " + e.getClass().getSimpleName());
}
Output
square(6): 36
Blocked: AssertionError: MathUtils cannot be instantiated
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms