What is the difference between a public abstract class with a public constructor, and a public class with a protected constructor. We don’t have any functions that are abstract in our abstract class, but we want programmers to only be capable of creating objects that extend that class.
Both scenarios compile and work, however I don’t understand which would be better to use in what scenario. I have been brought up to understand that although you cannot instantiate an abstract class directly (only through a non abstract child class), the abstract class should normally contain abstract functions that are required to be implemented by the children of that class.
Wouldn’t having a protected constructor in a public class signify that instantiation of this class is not possible (this is the only constructor we have).
MSDN states about using the
abstractkeyword for classes: Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. That is, it is not required that an abstract class contain any abstract members. Theabstractmodifier is just an explicit way to say that the class shouldn’t be instantiated, rather than with technical obstacles such as making constructors publicly invisible.Note that the technical obstacle you described even has a caveat: It can still be called:
Both mean that other developers who are just (ab-?)using your class can do something you did not intend to happen, namely instantiate your class, and both are not possibly when making the class abstract.
Therefore, the answer is that you should mark your classes as
abstract.Note that it is adviseable to make the constructor of your abstract class protected nonetheless (to emphasize that the class cannot be instantiated). Tools such as FxCop will output a warning if an abstract class has a public constructor.
This complies with the general rule of making each member just as visible as it really needs to be. In an abstract class, constructors will never be invoked from public scope, so
publicvisibility is not required. They will only ever be invoked by constructors of derived classes, soprotectedis the reasonable visiblity for any constructors in an abstract class.Hence, also make any constructors of your abstract classes (at most)
protected.