Why would anyone declare a constructor protected? I know that constructors are declared private for the purpose of not allowing their creation on stack.
Modifiers public, protected and, private are allowed with constructors. We can use a private constructor in a Java while creating a singleton class.
What is true about protected constructor? Explanation: Protected access modifier means that constructor can be accessed by child classes of the parent class and classes in the same package.
You make a constructor public if you want the class to be instantiated from any where. You make a constructor protected if you want the class to be inherited and its inherited classes be instantiated.
When a class is (intended as) an abstract class, a protected constructor is exactly right. In that situation you don't want objects to be instantiated from the class but only use it to inherit from.
There are other uses cases, like when a certain set of construction parameters should be limited to derived classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With