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.
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());
}
square(6): 36
Blocked: AssertionError: MathUtils cannot be instantiated
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