Why is it possible to write constructor for an abstract class in C#?
As far as I know we can't instantiate an abstract class.. so what is it for?
You can't instantiate the class, right?
15 Answers
Because there might be a standard way you want to instantiate data in the abstract class. That way you can have classes that inherit from that class call the base constructor.
public abstract class A{
private string data;
protected A(string myString){
data = myString;
}
}
public class B : A {
B(string myString) : base(myString){}
}
-
3But abstract class is defined as a class which we cant instantiate it.. if I use it to initialize an readonly variable on base class which is abstract is it okay?– MulderCommented Apr 8, 2011 at 23:37
-
8Yes, if I understand you correctly. You can't instantiate the abstract class itself but the derived class still has all the pieces of the base class. Its not only valid to do it, its one of the primary reasons why you would do it. Commented Apr 8, 2011 at 23:39
-
ok , now if I have a first level abstract class which inherits from other abstract class(second level) and third class ( not abstract class) inherit from the second layer abstract class, how can I initialize a readonly variable which is declared on the first layer abstract class from within the c'tor of the third normal class I need to go up two levels up to the c'tor– MulderCommented Apr 8, 2011 at 23:57
-
1The only way I really can think to do that is something like the following: public abstract class A { protected readonly string data; protected A(string myData) { data = myData; } } public abstract class B :A { protected B(string myData): base(myData){ } } public class C : B { C(string myData): base(myData){ } } Commented Apr 9, 2011 at 0:11
-
So when you call new B() does it call the constructor on the parent class?– ndtrevivCommented Oct 8, 2020 at 14:00
Far as I know we can't instantiate an abstract class
There's your error right there. Of course you can instantiate an abstract class.
abstract class Animal {}
class Giraffe : Animal {}
...
Animal animal = new Giraffe();
There's an instance of Animal right there. You instantiate an abstract class by making a concrete class derived from it, and instantiating that. Remember, an instance of a derived concrete class is also an instance of its abstract base class. An instance of Giraffe is also an instance of Animal even if Animal is abstract.
Given that you can instantiate an abstract class, it needs to have a constructor like any other class, to ensure that its invariants are met.
Now, a static class is a class you actually cannot instantiate, and you'll notice that it is not legal to make an instance constructor in a static class.
-
4From a terminology perspective, if
Foo
is an inheritable concrete type, andDerivedFoo:Foo
, what term would you use to describe a heap object instance which will report its type asFoo
, as distinct fromDerivedFoo
? My own inclination would be to use the phrase "an instance of T" to refer to something whose exact type is T. Otherwise I'd be inclined to say something like "a T or some derivative", "some derivative of T", "some implementation of T", or "something satisfying T" depending upon whether T is a concrete class, abstract class, interface, or constraint.– supercatCommented Sep 3, 2013 at 17:39 -
44Using that logic you can get instances of interfaces :-) Commented Jan 9, 2014 at 20:25
-
11@Eric msdn.microsoft.com/en-us/library/sf985hc5.aspx Says abstract class cannot be instantiated– NipunaCommented Jul 9, 2014 at 6:21
-
4@M.Babcock: The static initializers are run, but no instance of the type is created. Commented Nov 26, 2014 at 14:43
-
4@supercat Unfortunately that's a semantic misunderstanding that leads to misuse of polymorphism. A Giraffe "IS A" Animal. An instance of Giraffe is an instance of Animal also, and must be usable in every place where an instance of Animal is required. Eric is absolutely correct here. Insisting that the instance of Giraffe is not exactly an instance of Animal can lead to dangerous anti-patterns like allowing Rectangle be a subclass of Square even though it is does not maintain the same invariants and is not strictly substitutable. Commented Sep 22, 2015 at 14:48
It's a way to enforce a set of invariants of the abstract class. That is, no matter what the subclass does, you want to make sure some things are always true of the base class... example:
abstract class Foo
{
public DateTime TimeCreated {get; private set;}
protected Foo()
{
this.TimeCreated = DateTime.Now;
}
}
abstract class Bar : Foo
{
public Bar() : base() //Bar's constructor's must call Foo's parameterless constructor.
{ }
}
Don't think of a constructor as the dual of the new
operator. The constructor's only purpose is to ensure that you have an object in a valid state before you start using it. It just happens to be that we usually call it through a new
operator.
-
10You don't need to call
base()
on derived class' constructor. It will get called automatically, because that's the parameterless constructor. This means that your constructor is equivalent topublic Bar() {}
. Commented Nov 14, 2011 at 17:26 -
1@RobertKoritnik - that's odd since I can't recall or even imagine a time when I did not know that but there it is. Commented Mar 20, 2013 at 23:29
-
4side note/comment; I like the fact that you used the words; odd and even in the same sentence. Commented Oct 6, 2016 at 22:44
Adding to the above answers and examples.
Yes, an abstract class can have a constructor, even though an abstract class cannot be instantiated. An abstract class constructor c# code example will be explained. But, the next question can also be arises, as if we cannot instantiate (construct an object using new) an abstract class, then what for a constructor is in an abstract class or why should we use a constructor in abstract class?
Note that when we create an object of a derived class then the constructor of the abstract base class is implicitly called, even though we cannot instantiate an abstract class. For example in the program, if we create an object of a derived class then the abstract base class constructor will also be called.
This is also one of the example
Examples
abstract class A
{
protected A() {Console.WriteLine("Abstract class constructor"); }
}
//Derived class
class B : A
{
public B() {Console.WriteLine("Derived class constructor"); }
}
class Program
{
static void Main(string[] args)
{
B obj = new B();
}
}
Output will be
Abstract class constructor
Derived class constructor
Key Points About Abstract Class
- An abstract class cannot be instantiated.
- An abstract class can have constructor and destructor.
- An abstract class cannot be a sealed class because the sealed modifier prevents a class from being inherited.
- An abstract class contains abstract as well as non-abstract members.
- An abstract class members can be private, protected and internal.
- Abstract members cannot have a private access modifier.
- Abstract members are implicitly virtual and must be implemented by a non-abstract derived class.
It's there to enforce some initialization logic required by all implementations of your abstract class, or any methods you have implemented on your abstract class (not all the methods on your abstract class have to be abstract, some can be implemented).
Any class which inherits from your abstract base class will be obliged to call the base constructor.
You are absolutely correct. We cannot instantiate an abstract class because abstract methods don't have any body i.e. implementation is not possible for abstract methods. But there may be some scenarios where you want to initialize some variables of base class. You can do that by using base keyword as suggested by @Rodrick. In such cases, we need to use constructors in our abstract class.
Normally constructors involve initializing the members of an object being created. In concept of inheritance, typically each class constructor in the inheritance hierarchy, is responsible for instantiating its own member variables. This makes sense because instantiation has to be done where the variables are defined.
Since an abstract class is not completely abstract (unlike interfaces), it is mix of both abstract and concrete members, and the members which are not abstract are needed to be initialized, which is done in abstract class's constructors, it is necessary to have constructors in the abstract class. Off course the abstract class's constructors can only be called from the constructors of derived class.
Using abstract classes is a way of standardizing your code. It can also be considered as a way of preparing a template or blueprint for other classes. Think about different types of cars that are available now days :- SUV, Sedan, Coupe, Hatchback etc. All have the same basic blueprint, for instance they all have steering, brake, clutch etc. But still there are many features and functionalities that are different in all the cars. So we can think of it as that an abstract class of car has been declared that includes the standardized methods/features that need to be implemented by all the cars but additionally the different types of cars can add their own features/functionalities as well. Now coming to your question and relating it to the example given above. See if we have to make a car obviously it would be one of a kind mentioned above (SUV,Sedan.....) i.e. for creating an instance of abstract class we need to inherit it. That is why it is termed as "must inherit class". If the constructor is also being included in the abstract class then it means that all the derived classes would also need to use a constructor as well. And if we are running a code of this kind :-
public abstract class AbstractClass
{
public AbstractClass()
{
Console.WriteLine("Abstract class constructor");
}
}
public class derived : AbstractClass
{
public derived()
{
Console.WriteLine("Derived class constructor");
}
}
class Program
{
public static void Main(string[] args)
{
derived d= new derived();
Console.ReadLine();
}
}
Then the output would be :-
Abstract class constructor
Derived class constructor
which clearly shows that constructor can also be used in abstract classes.
You can instantiate it after you implemented all the methods. Then the constructor will be called.
I too want to make some shine on abstract surface All answer has covered almost all the things. Still my 2 cents
abstract classes are normal classes with A few exceptions
- You any client/Consumer of that class can't create object of that class, It never means that It's constructor will never call. Its derived class can choose which constructor to call.(as depicted in some answer)
- It may has abstract function.
Defining a constructor with public or internal storage class in an inheritable concrete class Thing
effectively defines two methods:
A method (which I'll call
InitializeThing
) which acts uponthis
, has no return value, and can only be called fromThing
'sCreateThing
andInitializeThing
methods, and subclasses'InitializeXXX
methods.A method (which I'll call
CreateThing
) which returns an object of the constructor's designated type, and essentially behaves as:Thing CreateThing(int whatever) { Thing result = AllocateObject<Thing>(); Thing.initializeThing(whatever); }
Abstract classes effectively create methods of only the first form. Conceptually, there's no reason why the two "methods" described above should need to have the same access specifiers; in practice, however, there's no way to specify their accessibility differently. Note that in terms of actual implementation, at least in .NET, CreateThing
isn't really implemented as a callable method, but instead represents a code sequence which gets inserted at a newThing = new Thing(23);
statement.
an abstract class can have member variables that needs to be initialized,so they can be initialized in the abstract class constructor and this constructor is called when derived class object is initialized.
From https://msdn.microsoft.com/en-us/library/ms182126.aspx
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.
Since only derived classes can use an abstract class constructor then an abstract class constructor, if needed, must be declared as protected
.
However, that said VS compiler will not complain (with default rules) when declaring public constructors in abstract classes however it will not allow creating a new instance.
There are two following important features that prevent to inherit Abstract class
Abstract class must have an abstract method otherwise it is not a abstract class
Abstract class must be inherited by derived class,So if a class inherited by other class than what is use of to create object of that class
-
1i believe you first point to be incorrect, it is very possible to have an abstract class without any abstract methods. Commented Jan 25, 2018 at 6:35