Constructor for abstract classes!

Source: Internet
Author: User

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!

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.