Singer and Android developer Donn Felker explores Joshua Bloch’s fourth Item: Enforce noninstantiability with a private constructor.
Stay tuned, cause we got more of these quick ones coming.
Enforce noninstantiability with a private constructor.
Examples where you don’t want class to be instantiated
- class that groups static methods and static fields (Util like classes think java.lang.Math/java.util.Arrays)
- class that groups static methods (including factory methods) for objects implementing specific interfaces (think java.util.Collections)
- class that group methods on a final class (vs. extending the class)
- Makes no sense to instantiate such “Util” classes
- Private constructors prevent instantiation
- Important side effect: prevents subclassing