Enforce noninstantiability with a private constructor

If we need a class NOT to be instantiated then, a private constructor with a throwable inside is the best way according to Effective Java book. As the constructor is private, the throwable AssertionError is mainly for reflection and for the class itself because private constructors can be called from the class itself.

public class EffectiveJavaBook {
    
    private EffectiveJavaBook () {
        throw new AssertionError();
    }
}

More about private constructor

  • The only way to ensure no instantiation is to add a private constructor which ensures the default constructor is not generated.
  • A private constructor prevents inheritance because the super constructor cannot be called. So it is not needed to declare the class as final.
  • Making a class abstract doesn’t work because can be subclassed and then instantiated.
  • With an abstract class, the user may think the class is for inheritance.
  • Throw an error in the private constructor avoids call it within the class and also for reflection.

FAQ

Following are some frequently asked questions:

Relection can call the private constructor, how to prevent it?

Answer:
We can throw an exception inside the private constructor in order to stop reflection calling the private constructor.

// Noninstantiable utility class
public class MyUtilityClass {
    // Suppress default constructor for noninstantiability
    private MyUtilityClass() {
        throw new AssertionError();
    }
}

Is AssertionError is the correct throwable in a private constructor?

Answer:
Yes, AssertionError is the correct throwable in a private constructor. According to Effective java book this private constructor is to suppress default constructor for noninstantiability. The following code would be ideal.

// Noninstantiable utility class
public class MyUtilityClass {
    // Suppress default constructor for noninstantiability
    private MyUtilityClass() {
        throw new AssertionError("Suppress default constructor for noninstantiability");
    }
}