This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Constructors can be declared as private. A private constructor means only code within the class itself can instantiate an object of that type, so if the private constructor class wants to allow an instance of the class to be used, the class must provide a static method or variable that allows access to an instance created from within the class.
Originally posted by M SRILATHA: Constructors can be declared as private. .....so if the private constructor class wants to allow an instance of the class to be used, the class must provide a static method or variable that allows access to an instance created from within the class.
I did not get this.Can you be a little clear,please?
The classic example stems from the singleton design pattern. You can find tons of literature on that. but...
if you have a static method, that method can be called even if no instance of the class has been created (think of all the Math class functions).
Now, those static functions are part of the class, so those methods CAN call private functions of the class. So, if the constructors are private, you can call the (public) static methods, which can then call the constructors. the static method then returns the reference to the object.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
sometimes, we can restrict that the objects of our class can built by the methods of the same class only(for getting the singleton property or for some other specific needs). In some cases, the public constructor will call the private one, for some manipulations.