If a public constructor in an abstract class can only be called by their derived classes it should be functionally equivalent to a protected constructor. Right?
Is there any difference in declaring a public constructor, instead of a protected one, in an abstract class? What would you use it for? Why the compiler doesn't complaint?
A constructor is used to initialize an object not to build the object. As we all know abstract classes also do have a constructor. So if we do not define any constructor inside the abstract class then JVM (Java Virtual Machine) will give a default constructor to the abstract class.
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.
If so what is the use? Answer: Yes, an abstract class can have a constructor. In general, a class constructor is used to initialize fields. Along the same lines, an abstract class constructor is used to initialize fields of the 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.
Absolutely correct. You should favor the protected constructor.
EDIT: no the compiler doesn't complain, but tools like FxCop (& Code Analysis) do. I believe there are some weird reflection tricks you can do with public constructors on abstract classes, but from a standpoint where you are merely providing base class functionality to other developers writing subclasses, stick with the protected constructor.
You are correct. A public constructor in an abstract class is functionally equivalent to a protected constructor.
I prefer to use a protected constructor in this case.
While, it is true that the compiler will not complain about you doing this, the compiler will complain about trying to generate an instance of the abstract class. Visual Studio is smart enough, as well, to not provide Intellisense if you try to instantiate the abstract 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