Preventing Instantiation with Private Constructors
What you'll learn: How to use a private constructor to stop anyone from creating instances of your utility class.
Why Utility Classes Shouldn't Be Instantiated
Utility classes exist solely to hold static methods and fields—they're collections of helpful functionality, not blueprints for objects. Think of a utility class like a cookbook: you use its recipes (static methods), but you'd never try to "create" a cookbook object to cook with. Creating an instance would be pointless and wastes memory.
By default, if you don't write any constructor, the compiler provides a public default constructor. This allows anyone to accidentally write new MathUtils(), which serves no purpose.
The Solution: A Private Constructor
Make the constructor private so it's only accessible within the class itself. Since utility classes never need to instantiate themselves, this effectively prevents all object creation:
public class MathUtils {
// Private constructor prevents instantiation
private MathUtils() {
// Optionally throw an exception to prevent reflection-based instantiation
}
public static int square(int x) {
return x * x;
}
}
Now this won't compile:
MathUtils utils = new MathUtils(); // Compilation error!
But this works perfectly:
int result = MathUtils.square(5); // Works! Uses static method
Why This Matters
Private constructors communicate intent to other developers: "Don't instantiate this class." They prevent mistakes and enforce best practices for utility class design.
Key Takeaway: Always give utility classes a private constructor to prevent accidental instantiation—utility classes should only provide static methods, never objects.