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?
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.
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.
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.
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.
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.
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.
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