Facts to declaring a constructor as private
1. It does not make any sense to make the instance utility class, i.e. all methods are static (e.g. java.util.Arrays or java.util.Collections). To control over this instantiation => make constructor private.
2. In factory pattern or singleton pattern, where user wants to control on the way to create instances of the class.
3. In case of inner class, making constructor private allows instantiations of class inside the outer class only. It is better approach to declare the inner class private from the start.
4. You don't want someone else to inherit your class, having a single and private constructor helps you with that, although it disables you from creating instances of your own class. A better approach is to declare your class final from the start.
No comments:
Post a Comment