As we all know, abstract classes cannot be instantiated. Can there be constructors in abstract classes?
Many beginners have similar questions!
The answer is yes, and if we do not define it ourselves, the compiler will generate a default constructor for us. Let's look at this Code:
Public abstract class MyAbstractClass
{
}
We didn't define the constructor ourselves. We used the ILDasm tool to look at the generated IL code:
. Method family hidebysig specialname rtspecialname
Instance void. ctor () cel managed
{
// Code size 7 (0x7)
. Maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib] System. Object:. ctor ()
IL_0006: ret
} // End of method MyAbstractClass:. ctor
It should be noted that the compiler indeed generates a default constructor for us!
Why is this design?
It is easy to understand that abstract classes need to be inherited by other classes. These subclasses need to be instantiated. when instantiating a subclass, the constructor of the subclass needs to be called. By default, before calling the constructor of a subclass, you must call the constructor of the base class. This is the same as that of a non-abstract class!
In fact, the following test can be performed: class Program
{
Static void Main (string [] args)
{
MyEntityClass a = new MyEntityClass ();
}
}
Public abstract class MyAbstractClass
{
Public MyAbstractClass ()
{
Console. WriteLine ("the non-argument constructor of the abstract class is called! ");
}
}
Public class MyEntityClass: MyAbstractClass
{
}
The running result is: the non-argument constructor of the abstract class is called!
The constructor calls the non-argument constructor of the base class by default. This is the same as the non-abstract class!