Prevent Accidental Instantiation with Private Constructor in Java

Post 4 - Sharing a learning from Effective Java Item 4: Enforce Noninstantiability with a Private Constructor Some classes are not meant to be instantiated (e.g. utility classes). But Java adds a public constructor by default if you don’t define one. ❌ Problematic utility class: public class MathUtils { public static int add(int a, int b) { return a + b; } } This allows: new MathUtils(); // unwanted ✅ Correct approach: public class MathUtils { private MathUtils() { throw new AssertionError("No instances allowed"); } public static int add(int a, int b) { return a + b; } } Why this matters: • Prevents accidental instantiation • Makes intent explicit • Improves API design clarity Key takeaway: If a class is not meant to be instantiated, make it impossible to do so. 📖 Effective Java — Joshua Bloch #Java #EffectiveJava #CleanCode #BackendEngineering #SoftwareEngineering #DesignPrinciples #JavaTips #ProductEngineering

To view or add a comment, sign in

Explore content categories