My first question: What is the difference between an protected and a public constructor in an abstract class?
My second questions: Does it make sense, if the abstract class has an private constructor?
Thanks in advance!
After all, an abstract class cannot be created directly – only via a derived instance. Consequently, it is only the derived classes for whom it makes sense to access the constructor in the first place. Hence, ReSharper recommends that you make the constructor protected .
Constructor is always called by its class name in a class itself. A constructor is used to initialize an object not to build the object. As we all know abstract classes also do have a constructor.
A private constructor in an abstract class can also serve the purpose of sealed classes (like in Scala or Kotlin etc.). Since you can still provide subclasses from within the abstract class, but outsiders cannot extend/implement (as @Marko Topolnik answered).
We can't create public and private constructors simultaneously in a class, both without parameters. We can't instantiate the class with a private constructor. If we want to create an object of a class with private constructor then, we need to have public constructor along with it.
One possible design that would use a private constructor on an abstract class:
public abstract class BaseClass
{
private BaseClass(Object param)
{
//Do something with parameters
}
//Provide various methods that descendant classes will know how to perform
public static BaseClass FromObject(Object value)
{
//Based on object, choose which type of derived class to construct...
}
private class HiddenDerivedA : BaseClass
{
public HiddenDerivedA(Object value)
: base(value)
{
}
}
private class HiddenDerivedB : BaseClass
{
public HiddenDerivedB(Object value)
: base(value)
{
}
}
}
This pattern is useful if the derived implementations are tightly coupled to the selection logic used to construct them and you wish to provide a high degree of insulation from the rest of your code. It relieves you of the responsibility of having to support other inheritors besides those you explicitly intended and allows you to expose all private state from the base class to your derived classes.
Question #1: Not much. You can't call the constructor of an abstract class (instantiate it) directly anyway. You could only call one from a subclass, which means you'd definitely have access to protected members as well as public members at that point.
Question #2: No, not much sense. A private constructor on an abstract class could only be called by "constructor chaining" from a non-private constructor in the same class.
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