Is there any relevance of a 'public' constructor in an abstract class? I can not think of any possible way to use it, in that case shouldn't it be treated as error by compiler (C#, not sure if other languages allow that).
Sample Code:
internal abstract class Vehicle
{
public Vehicle()
{
}
}
The C# compiler allows this code to compile, while there is no way i can call this contructor from the outside world. It can be called from derived classes only. So shouldn't it allow 'protected' and 'private' modifiers only. Please comment.
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.
You make a constructor public if you want the class to be instantiated from any where. You make a constructor protected if you want the class to be inherited and its inherited classes be instantiated.
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 .
Constructors in programming are the methods that are called automatically when an object is initialized. The constructor's purpose is to initialize the object. Constructors should always be public and they are declared without any return type.
There's no reason for a public constructor for an abstract class. I'd assume that the reason that the compiler doesn't complain is as simple that they just didn't spend time covering that since it really doesn't matter if it's public or protected.
Inside an abstract class, for an instance constructor, modifiers public
, protected internal
, and protected
are all equivalent. Then internal
is more strict than them, and private
is the most strict access.
If all instance constructors are private
, only classes nested inside the class in question can inherit from it.
Note: If no instance constructors are given for a non-static class, then the compiler will generate one by itself. That's a constructor taking zero arguments. If the class is abstract, that auto-generated constructor is protected
. Otherwise it is public
.
The only situation I can think of where it makes a difference if an instance constructor of an abstract class is public
or protected
, is when you use reflection. As an example, saying
ConstructorInfo[] ctors = typeof(Vehicle).GetConstructors();
will give an empty array if the sole constructor is protected
, and a length-1 array if it's public
. But of course there are overloads that specify BindingFlags
, so this is not a problem, just something to remember if one uses reflection.
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