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?
Joined: Apr 07, 2002
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.
Joined: Apr 05, 2000
In the case of a protected ctor in a base class the derived class could invoke super() in its ctor.
The only reason for time is so that everything doesn't happen all at once.
- Buckaroo Banzai
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...
Joined: Dec 20, 2001
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