Noninstantiable classes are those which can be invoked using object creation.We prefer classes to be Noninstantiable if you want the class to be Utility class with static methods and variables in it.

public final class Useless {
    private Useless() {}
}

A private constructor is the normal object-oriented solution. However, it would still be possible to instantiate such a class using reflection, like this:

Constructor<Useless> con = Useless.class.getDeclaredConstructor();
con.setAccessible(true); // bypass "private"
Useless object = con.newInstance();

To prevent even reflection from working, throw an exception from the constructor:

public final class Useless {
    private Useless() {
        throw new UnsupportedOperationException();
    }
}

Dont Use absract class for NonInstantiable classes

Attempting to enforce noninstantiability by making a class abstract does not work. The class can be subclassed and the subclass instantiated. Furthermore, it misleads the user into thinking the class was designed for inheritance

Comments are closed.