Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are practical uses of a protected constructor?

Why would anyone declare a constructor protected? I know that constructors are declared private for the purpose of not allowing their creation on stack.

like image 420
Amol Gawai Avatar asked Jun 29 '09 08:06

Amol Gawai


People also ask

Can we use protected in constructor?

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 the true about protected constructor?

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.

Should constructors be public or protected?

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.


1 Answers

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.

like image 185
Henk Holterman Avatar answered Sep 27 '22 02:09

Henk Holterman