Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should constructors on abstract classes be protected, not public?

ReSharper suggests changing the accessibility of a public constructor in an abstract class to protected, but it does not state the rationale behind this.

Can you shed some light?

like image 515
Cristian Diaconescu Avatar asked Apr 17 '09 19:04

Cristian Diaconescu


People also ask

Can abstract class constructor be public?

Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed.

Can constructor of abstract class be private?

Answer: Yes. Constructors in Java can be private. All classes including abstract classes can have private constructors. Using private constructors we can prevent the class from being instantiated or we can limit the number of objects of that class.

Why do we need constructors inside abstract class?

The main purpose of the constructor is to initialize the newly created object. In abstract class, we have an instance variable, abstract methods, and non-abstract methods. We need to initialize the non-abstract methods and instance variables, therefore abstract classes have a constructor.

Why are constructors protected?

A protected constructor means that only derived members can construct instances of the class (and derived instances) using that constructor. This sounds a bit chicken-and-egg, but is sometimes useful when implementing class factories. Technically, this applies only if ALL ctors are protected.


2 Answers

Simply because being public makes no sense in an abstract class. An abstract class by definition cannot be instantiated directly. It can only be instantiated by an instance of a derived type. Therefore the only types that should have access to a constructor are its derived types and hence protected makes much more sense than public. It more accurately describes the accessibility.

like image 146
JaredPar Avatar answered Sep 22 '22 01:09

JaredPar


It technically makes no difference whatsoever if you make the constructor public instead of protected on an abstract class. The accessibility/visibility of the constructor is still exactly the same: the same class or derived classes. The two keywords have indistinguishable effects for all intents and purposes.

So, this choice is only a matter of style: type protected to satisfy the Object Oriented savvy people.


Reflection will by default only include the constructor when it is public, but you cannot call that constructor anyway.

IntelliSense will show the public constructor when typing new, but you cannot call that constructor anyway.

The assembly's metadata will reflect the fact that the constructor is public or protected.

like image 23
Daniel A.A. Pelsmaeker Avatar answered Sep 21 '22 01:09

Daniel A.A. Pelsmaeker