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.
Theoritically protected is allowed as an access specifier for a ctor of a constructor. but when you cannot instantiate it in a derived class of a different package using its own reference (like the base class ref) then what is the use of this ? where and how can the class be instantiated? is it only in the pacakage?
Based on previous discussion of protected methods in different packages, I understand that you cannot use the base reference b1 in this derived class but I cannot understand why you cannot create a base instance and cast it to derived reference. what are the restrictions of protected access specifier when it comes to constructors?
Hi Malini, protected (and private) constructors are, for example, used in singletons. This pattern ensures that there is only a single instance of the object. The instantiation of the object is done in a static method, usually called something like getInstance(), which returns the instance of the existing class, or, if no instance exists, a new instance. Hope this helps.
How does the protected ctor help in singleton patterns? i thought you could use only private constructors for that to ensure that the ctor is not used outside the class. In case of a protected ctor you could instantiate it from a derived class in the same package. so may be protected ctors aren't that useful in singleton patterns...
In general, classes that implement a singleton pattern are not extended. It may be possible to do so, but the details would become very complicated. I'm not even sure if it would be useful (or feasible) to do so. Of course, making a constructor protected makes it accessible to classes within the same package, as well as to subclasses outside of that package. As I just mentioned, there probably won't be any subclass, so we won't even worry about that case. However, the fact that other classes within the same package can instantiate the class through a protected constructor pretty much destroys the usefulness of the singleton pattern. To properly implement a singleton pattern, you should use a private constructor so that the class itself can have control over how many are created. Corey