Feb 13, 2008

Private constructor



Private constructor
Topic:

Private constructors prevent a class from being explicitly instantiated by callers.

There are some common cases where a private constructor can be useful :

* classes containing only static utility methods
* classes containing only constants
* type safe enumerations
* singletons

These examples fall into two categories.
Object construction is entirely forbidden
No objects can be constructed, either by the caller or by the native class. This is only suitable for classes that offer only static members to the caller.

In these cases, the lack of an accessbile constructor says to the caller : "There are no use cases for this class where you need to build an object. You can only use static items. I am preventing you from even trying to build an object of this class." See class for constants for an illustration.

If the programmer does not provide a constructor for a class, then the system will always provide a default, public no-argument constructor. To disable this default constructor, simply add a private no-argument constructor to the class. This private constructor may be empty. Somewhat paradoxically, creation of objects by the caller is in effect disabled by the addition of this private no-argument constructor.
Object construction is private only
Objects can be constructed, but only internally. For some reason, a class needs to prevent the caller from creating objects.

In the case of a singleton, the policy is that only one object of that class is supposed to exist. Creation of multiple objects of that class is forbidden.

In the case of JDK 1.4 type-safe enumerations, more than one object can be created, but again, there is a limitation. Only a specific set of objects is permitted, one for each element of the enumeration. (For JDK 1.5 enums, the creation of such objects is done implicitly by the Java language, not explicitly by the application programmer.)

See Also :
Type-Safe Enumerations
Class for constants
Factory methods
Singleton
Would you use this technique?
Yes No Undecided
Add your comment to this Topic :

Comment:

© 2008 Hirondelle Systems | Source Code | Contact | License | Quotes | RSS
Individual code snippets can be used under this license - Last updated on Dec 20, 2007.
Over 78,000 unique IPs (and 164,000 sessions) last month - Built with WEB4J.
- In Memoriam : Bill Dirani -

No comments: